It is very eays to connect spring boot 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>
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;
}
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.
}
1
2
3
@Repository
public interface StudentRepository extends CrudRepository<Student, String> {
}
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;
}
}