需求描述
一个查询List的需求,如果redis有,就直接从redis中获取List返回。如果没有,则先查询,再保存入redis中。使用RedisTemplate实现。
实现步骤
添加maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
@Configuration配置
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
String host = env.getProperty("redis.url");
Integer port = Integer.valueOf(env.getProperty("redis.port"));
String password = env.getProperty("redis.password");
// 单机配置
RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration();
standaloneConfig.setHostName(host);
standaloneConfig.setPort(port);
if (StringTools.isNotBlank(password)) {
standaloneConfig.setPassword(RedisPassword.of(password));
}
JedisConnectionFactory connectionFactory = new JedisConnectionFactory(standaloneConfig);
return connectionFactory;
}
@Bean
public RedisTemplate<Object, Object> getRedisTemplate(RedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
伪代码
@Autowired
private RedisTemplate redisTemplate;
@Override
@ExecTime
public List<TaskDto> getTaskDtoListUseCache(String uid) {
String key = getTaskRedisKey(uid);
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
List<TaskDto> taskDtoList = (List<TaskDto>) redisTemplate.opsForValue().get(key);
return taskDtoList;
}
else {
List<TaskDto> taskDtoList = getTaskDtoList(uid);
long expireTime = getTaskExpireTime();
redisTemplate.opsForValue().set(key, taskDtoList, expireTime, TimeUnit.SECONDS);
log.info("用户[{}]的任务列表数据缓存成功,过期秒数为:[{}]s", uid, expireTime);
return taskDtoList;
}
}
实体类需要实现序列化接口
public class TaskDto implements Serializable {
...
}
总结
可以发现,使用org.springframework.data.redis.core.RedisTemplate
,可以极大地简化Java对redis的操作。
可以直接把List等结果保存在redis中,需要的时候也可以很方便地进行反序列化。