Configure and Use Spring Data Redis


public class RedisConfiguration {

    public LettuceConnectionFactory redisConnectionFactory() {
        ConfigFile configFile = new ConfigFile();
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(configFile.getRedisHost());
        return new LettuceConnectionFactory(configuration);

    public StringRedisTemplate redisTemplate() {
        return new StringRedisTemplate(redisConnectionFactory());

You can use RedisTemplate instead of StringRedisTemplate.

Redis Repository

public class Student implements Serializable {
    public enum Gender { 
        MALE, FEMALE

    @Id private String id;
    private String name;
    private Gender gender;
    private int grade;
    // ...

The Spring Data Repository

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

Data Access Using StudentRepository

Saving a New Student Object

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

Retrieving an Existing Student Object

Student retrievedStudent = 

Updating an Existing Student Object

retrievedStudent.setName("Richard Watson");;

Deleting Existing Student Data


Find All Student Data

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


Install Redis on Ubuntu 20.04

sudo apt install redis-server

Configure Redis

sudo nano /etc/redis/redis.conf

find the line specifying the supervised directive. By default, this line is set to no. However, to manage Redis as a service, set the supervised directive to systemd (Ubuntu’s init system).

Secure Redis

sudo nano /etc/redis/redis.conf

locate the requirepass directive under the SECURITY section and uncomment it (by removing #).Once you have uncommented the line, replace foobared with the password of your choice.

sudo systemctl restart redis.service


Configure Spring Session with Redis