Spring Data – Part 6: Redis

No Comments


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:

C:\dev\bin\redis64>redis-server ./redis.conf
[5612] 09 Mar 10:34:15 * Server started, Redis version 2.4.5
[5612] 09 Mar 10:34:15 * DB loaded from disk: 0 seconds
[5612] 09 Mar 10:34:15 * The server is now ready to accept connections on port 6379
[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:

redis> ping
redis> SET foo bar
redis> GET foo

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


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

redis> SUBSCRIBE c1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "c1"
3) (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:

redis> PUBLISH c1 "hello redis"
(integer) 1

Doing this, the first client receives our message:

1) "message"
2) "c1"
3) "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:

<!-- Jedis Connection -->    
<bean id="jedisConnectionFactory" 
   p:host-name="localhost" p:port="6379" />
<!-- Redis Template -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
	<property name="connectionFactory" ref="jedisConnectionFactory" />
<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:

public class StringStringRepository {
   private RedisTemplate<String, String> template;	
   public void add(String key, String value) {
      template.opsForValue().set(key, value);
   public String getValue(String key) {
      return template.opsForValue().get(key);
   public void delete(String key) {

The usage of that template looks like this:

   @Autowired StringStringRepository repo;
   @Before public void setUp() {
      repo.add("foo", "bar");
   @Test public void shouldFindValue() {
      String value = repo.getValue("foo");
      Assert.assertNotNull("Value is <null>", value);
      Assert.assertEquals( "Value mismatch" , "bar", value);

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:

package redis;
public class User {
   private String login;
   private String fullName;
   private Date lastLogin;

The serializer itself is a property of the RedisTemplate:

<!-- Redis Template -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
	<property name="connectionFactory" ref="jedisConnectionFactory" />
	<property name="valueSerializer">
		<bean id="redisJsonSerializer" 
			<constructor-arg type="java.lang.Class" value="redis.User"/>

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

public class UserRepository {
	private RedisTemplate<String, User> template;	
	public void add(User user) {
		template.opsForValue().set(user.getLogin(), user);
	public User get(String key) {
		return template.opsForValue().get(key);

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


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


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


Your email address will not be published. Required fields are marked *