Spring Boot integration with Redis
Overview
This tutorial is introduction to Spring Boot integration Redis by Spring Data Redis, which provider the abstrations of the Spring Data platform to Redis, the popular in-memory data structure store.
Maven Dependencies
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Redis Configuration
java
@AutoConfiguration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
//set key serializer method String
redisTemplate.setKeySerializer(new StringRedisSerializer());
//set value serializer json,use GenericJackson2JsonRedisSerializer替换replace default serializer
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
setting properties in application.yml
yml
spring:
redis:
host: 127.0.0.1
port: 6379
Using template
if you have complete these step, now, you can Autowired the Redistemplate , for example next
java
@SpringBootTest
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void set() {
redisTemplate.opsForValue().set("name","lcd");
}
@Test
public void get() {
String name = (String) redisTemplate.opsForValue().get("name");
System.out.println("name");
Assertions.assertEquals(name,"lcd");
}
}
Conclusion
In this article. we went through the basic of Spring Boot Data Redis.