Springboot整合Redis
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 在springboot2.x之后, 原来使用的jedis被替换成了lettuce
配置
spring:
redis:
host: 127.0.0.1
port: 6379
测试
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
redisTemplate.opsForValue().set("key1", "aaa");
System.out.println(redisTemplate.opsForValue().get("key1"));
}
127.0.0.1:6379> keys *
1) "xacxedx00x05tx00x05user1"
通过自定义RedisTemplate, 使数据序列化
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) throws UnknownHostException {
//默认是<Object, Object>
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
//json序列化配置
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(mapper);
//string序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用string序列化
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
//value采用json序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
再次测试后
127.0.0.1:6379> keys *
1) "xacxedx00x05tx00x05user1"
2) "user1"