I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

This article is an introduction to Spring Data Redis, which provides the abstractions of the Spring Data platform to Redis – the popular in-memory data structure store.

Redis is driven by a keystore-based data structure to persist data and can be used as a database, cache, message broker, etc.

We’ll be able to use the common patterns of Spring Data (templates, etc.), while also having the traditional simplicity of all Spring Data projects.

2. Maven Dependencies

Let’s start by declaring the Spring Data Redis dependencies in the pom.xml:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.0.3.RELEASE</version>
 </dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
    <type>jar</type>
</dependency>

The latest versions of spring-data-redis and jedis can be downloaded from Maven Central.

3. The Redis Configuration

To define the connection settings between the application client and the Redis server instance, we need to use a Redis client.

There is a number of Redis client implementations available for Java. In this tutorial, we’ll use Jedis – a simple and powerful Redis client implementation.

There is good support for both XML and Java configuration in the framework; for this tutorial, we’ll use Java-based configuration.

3.1. Java Configuration

Let’s start with the configuration bean definitions:

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    return new JedisConnectionFactory();
}

@Bean
public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(jedisConnectionFactory());
    return template;
}

The configuration is quite simple. First, using the Jedis client, we’re defining a connectionFactory.

Then, we defined a RedisTemplate using the jedisConnectionFactory. This can be used for querying data with a custom repository.

3.2. Custom Connection Properties

You may have already noticed that the usual connection-related properties are missing in the above configuration. For example, the server address and port are missing in the configuration.The reason is simple: for our example, we’re using the defaults.

However, if we need to configure the connection details, we can always modify the jedisConnectionFactory configuration as follows:

@Bean
JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory jedisConFactory
      = new JedisConnectionFactory();
    jedisConFactory.setHostName("localhost");
    jedisConFactory.setPort(6379);
    return jedisConFactory;
}

4. Redis Repository

Let’s use a Student entity for our examples:

@RedisHash("Student")
public class Student implements Serializable {
  
    public enum Gender { 
        MALE, FEMALE
    }

    private String id;
    private String name;
    private Gender gender;
    private int grade;
    // ...
}

4.1. The Spring Data Repository

Let’s now create the StudentRepository as follows:

@Repository
public interface StudentRepository extends CrudRepository<Student, String> {}

5. Data Access using StudentRepository

By extending CrudRepository in StudentRepository, we automatically get a complete set of persistence methods that perform CRUD functionality.

5.1. Saving a New Student Object

Let’s save a new student object in the data store:

Student student = new Student(
  "Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.save(student);

5.2. Retrieving an Existing Student Object

We can verify the correct insertion of the student in the previous section by fetching the student data:

Student retrievedStudent = 
  studentRepository.findById("Eng2015001").get();

5.3. Updating an Existing Student Object

Let’s change the name of the student retrieved above and save it again:

retrievedStudent.setName("Richard Watson");
studentRepository.save(student);

Finally, we can retrieve the student’s data again and verify that the name is updated in the datastore.

5.4. Deleting an Existing Student Data

We can delete the above-inserted student data:

studentRepository.deleteById(student.getId());

Now we can search for the student object and verify that the result is null.

5.5. Find All Student Data

We can insert a few student objects:

Student engStudent = new Student(
  "Eng2015001", "John Doe", Student.Gender.MALE, 1);
Student medStudent = new Student(
  "Med2015001", "Gareth Houston", Student.Gender.MALE, 2);
studentRepository.save(engStudent);
studentRepository.save(medStudent);

We can also achieve this by inserting a collection. For that, there is a different method – saveAll() – which accepts a single Iterable object containing multiple student objects that we want to persist.

To find all inserted students, we can use the findAll() method:

List<Student> students = new ArrayList<>();
studentRepository.findAll().forEach(students::add);

Then we can quickly check the size of the students list or verify for a greater granularity by checking the properties of each object.

6. Conclusion

In this tutorial, we went through the basics of Spring Data Redis. The source code of the examples above can be found in a GitHub project.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
prashanth-g
Guest
prashanth-g

Can anyone help with an example for checking a key exists in RedisTemplate?

I am using redisTemplate.keys(“key”); to check whethre my key exists. Redis guys are telling not to use keys *

Eugen Paraschiv
Guest

So, skipping over the broader question of “should you use keys” – the RedisKeyCommands has a simple exists API you can use. Hope that helps.
Cheers,
Eugen.

Pramod Bhargava
Guest
Pramod Bhargava

There is a annotaion @EnableRedisRepository what it do?
how can i configure this in my configuration xml?

Grzegorz Piwowarek
Guest
Grzegorz Piwowarek

This is a Spring Data annotation that pretty much connects all the wires between Redis and Java code. Is there any reason why you need to stick to XML and not to Java config?

Pramod Bhargava
Guest
Pramod Bhargava

My application is still using .xml configurations .so we dont have @configuration which comes with spring boot

Eugen Paraschiv
Guest

You’ll need to use some Java configuration to be able to use the annotation. However, keep in mind that moving to Java config is not an all or nothing choice. You can gradually make the move and still keep most of your XML configuration intact, and then slowly move that when you can.

Bartosz Jaszczak
Guest
Bartosz Jaszczak

I’ve got one question, is there a proper way to test Redis repositories/connections/entities? I’m using Spring Data Redis, and trying to write some tests for it. I’ve found projects like com.github.kstyrc.embedded-redis, but i dont like idea of alpha version of library with last commit 10 months ago in production dependencies. Should i use real/test redis instance? Is there any spring supported way to use embedded one? (I’ve moved my question from topic about client)

Eugen Paraschiv
Guest

I’ve never tried to run an embedded instance, so I’m not sure how stable/mature they are. I’ve always used an actual instance, but I’d be curious to know if there’s good embedded support as well.
Not much help on this one.
Cheers,
Eugen.