Beliebte Suchanfragen

Cloud Native

DevOps

IT-Security

Agile Methoden

Java

//

Spring Data – Part 6: Redis

26.4.2012 | 4 minutes of reading time

Redis

Redis [1] is a NoSQL [2] key/value datastore. Think of it as a big, very fast persistent hashmap. Redis offers a master/slave data replication [3] and also a built-in publish/subscribe messaging system [4].

It is implemented in C and can be built on your favourite platform. Just grab the tar from the download page [5] or use the precompiled binaries for Windows [6] (that’s what I did).

After compiling or downloading, open a shell in your Redis folder an start the server by typing:

1C:\dev\bin\redis64>redis-server ./redis.conf
2[5612] 09 Mar 10:34:15 * Server started, Redis version 2.4.5
3[5612] 09 Mar 10:34:15 * DB loaded from disk: 0 seconds
4[5612] 09 Mar 10:34:15 * The server is now ready to accept connections on port 6379
5[5612] 09 Mar 10:34:16 - DB 0: 1 keys (0 volatile) in 4 slots HT.

Open another shell and start the Redis client by typing:

1C:\dev\bin\redis64>redis-cli
2redis 127.0.0.1:6379> ping
3PONG
4redis 127.0.0.1:6379> SET foo bar
5OK
6redis 127.0.0.1:6379> GET foo
7"bar"

We ping the server and set and lookup a string based key/value pair.

Publish/Subscribe

Now let’s have a look at the publish/subscribe messaging. Type:

1CLIENT 0:
2redis 127.0.0.1:6379> SUBSCRIBE c1
3Reading messages... (press Ctrl-C to quit)
41) "subscribe"
52) "c1"
63) (integer) 1

The current client is now subscribed to a channel c1 and is listening to incoming messages. Start yet another shell and send a message to channel c1:

1CLIENT 1:
2C:\dev\bin\redis64>redis-cli
3redis 127.0.0.1:6379> PUBLISH c1 "hello redis"
4(integer) 1
5redis 127.0.0.1:6379>

Doing this, the first client receives our message:

1CLIENT 0:
21) "message"
32) "c1"
43) "hello redis"

There are much more commands than this. Try them by yourself.

Spring Data Redis

Spring Data Redis does not offer a repository abstraction like other Spring Data proejcts (e.g. Spring Data Mongo DB or Spring Data JPA ). Instead it relies on the well-known template approach often used in Spring.

Let’s start with a very simple example. We will store key/value pairs of type String/String. Our Spring configuration looks basically like this:

1<!-- Jedis Connection -->    
2<bean id="jedisConnectionFactory" 
3   class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
4   p:host-name="localhost" p:port="6379" />
5 
6<!-- Redis Template -->
7<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
8    <property name="connectionFactory" ref="jedisConnectionFactory" />
9</bean>
10 
11<bean class="redis.StringStringRepository"/>

We are using the Jedis connection factory to connect to our Redis node via TCP/IP and define the RedisTemplate we are using in our StringStringRepository. We introduce the repository in order to encapsulate the template itself, so that our developers do not need to know anything about the persistence layer:

1public class StringStringRepository {
2   @Autowired
3   private RedisTemplate<String, String> template;	
4 
5   public void add(String key, String value) {
6      template.opsForValue().set(key, value);
7   }
8 
9   public String getValue(String key) {
10      return template.opsForValue().get(key);
11   }
12 
13   public void delete(String key) {
14      template.opsForValue().getOperations().delete(key);
15   }
16}

The usage of that template looks like this:

1@Autowired StringStringRepository repo;
2 
3   @Before public void setUp() {
4      repo.add("foo", "bar");
5   }
6 
7   @Test public void shouldFindValue() {
8      String value = repo.getValue("foo");
9 
10      Assert.assertNotNull("Value is <null>", value);
11      Assert.assertEquals( "Value mismatch" , "bar", value);
12   }

Object storage

In a real world application, your business objects often are more complex than a simple string. Since the key/value pairs in Redis consist of byte arrays (both key and value), you can store anything you want. Spring Data Redis supports this by using an appropiate serialization mechanism.

Let’s assume we want to persist simple user object like this:

1package redis;
2 
3public class User {
4 
5   private String login;
6   private String fullName;
7   private Date lastLogin;
8   ...
9}

The serializer itself is a property of the RedisTemplate:

1<!-- Redis Template -->
2<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
3    <property name="connectionFactory" ref="jedisConnectionFactory" />
4    <property name="valueSerializer">
5        <bean id="redisJsonSerializer" 
6                        class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">
7            <constructor-arg type="java.lang.Class" value="redis.User"/>
8        </bean>   
9    </property>
10</bean>

We use a JSON serializer and provide the class to serialize (redis.User). An appropriate repository may look like this:

1public class UserRepository {
2 
3    @Autowired
4    private RedisTemplate<String, User> template;	
5 
6    public void add(User user) {
7        template.opsForValue().set(user.getLogin(), user);
8    }
9 
10    public User get(String key) {
11        return template.opsForValue().get(key);
12    }

The full source code of all the examples can be found at github .

Summary

We had a look at the basic features like writing and reading a key/value pair with Redis. I also showed you the publish/subscribe feature of Redis.

Then we persisted the same data with help of the Spring Data Redis API.

This is the last part of this blog series on the Spring Data project. I hope some of the articles were useful or at last a little bit interesting.

Spring Data Project

These are my other posts covering the Spring Data project:

Part 5: Spring Data Neo4j
Part 4: Geospatial Queries with Spring Data Mongo DB
Part 3: Spring Data Mongo DB
Part 2: Spring Data JPA
Part 1: Spring Data Commons

References

[1] Redis Homepage
[2] NoSQL databases
[3] Redis Replication
[4] Redis Messaging
[5] Redis Download
[6] Win32/64 Precompiled binaries

share post

Likes

0

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.