Spring Boot Redis Connection

Spring Boot Redis connection with simple steps. It's very easy to connect Spring Boot with redis.

Posted by dogukanhan on September 03, 2020 · 4 mins read

It is very eays to connect spring boot with redis.

1-)You must add these two dependencies to your application for connecting the application with redis.

1
2
3
4
5
6
7
8
9
10
11
<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

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

2-) Create JedisConnectionFactory and RedisTemplate bean for injection.

You may add thise two beans to the application class or you can add a class which is annotated with @Configuration.

1
2
3
4
5
6
7
8
9
10
11
 @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

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

3-) Create an entity class for representing your data in redis.

1
2
3
4
5
6
7
8
9
10
@RedisHash("Student")
public class Student implements Serializable {


    private String id;
    private String name;
    private int number;
	
	// Generate getter and setter methods.
}

4-) Create a repository interface for accessing yor data.

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

5-) Inject your repository interface and use it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@SpringBootApplication
public class RedisExampleApplication implements CommandLineRunner {
	
	// Injected repository interface.
	@Autowired
	private StudentRepository studentRepository;

    public static void main(String[] args) {
        SpringApplication.run(RedisExampleApplication.class, args);
    }

    @Override
     public void run(String... args) throws Exception {
		   // Do your logic here in a command line application with spring.
			 
        Student student = new Student();
        student.setName("test");
        student.setNumber(33);
        studentRepository.save(student); // Save a student.

        studentRepository.findAll().forEach(System.out::println); // List All Students.
    }
		
		// Beans requried for connection
		@Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

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