其实注解支持配置过期时间.
@Cacheable(value = "people#${select.cache.timeout:1800}#${select.cache.refresh:600}", key = "#person.id", sync = true)//3
public Person findOne(Person person) {
Person p = personRepository.findOne(person.getId());
System.out.println("为id、key为:" + p.getId() + "数据做了缓存");
return p;
}
代码实现, 通过重写RedisCacheManager类实现
- 分析源码后,我们可以在createCache方法上做文章,实现自己的cacheManage
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.util.Assert;
/**
* @author zhangminglei
*/
public class CustomizeRedis extends RedisCacheManager {
CustomizeRedis(RedisOperations redisOperations) {
super(redisOperations);
}
@Override
protected RedisCache createCache(String cacheName) {
Assert.hasText(cacheName, "CacheName must not be null or empty!");
String[] values = cacheName.split("#");
long expiration = computeExpiration(values);
return new RedisCache(values[0], (isUsePrefix() ? getCachePrefix().prefix(cacheName) : null), getRedisOperations(), expiration,
false);
}
private long computeExpiration(String[] values) {
if (values.length > 1) {
return Long.parseLong(values[1]);
}
// 如果说想使用默认的过期时间而不指定特殊时间,则可以直接@Cacheable(cacheNames="name"),不需要加'#过期时间'了
return super.computeExpiration(values[0]);
}
}
- 然后需要让cache使用我们的自定义CacheManager
// 为redis设定默认的序列化方式为StringRedisSerializer(默认为JdkSerializationRedisSerializer,不太方便查看内容)
@Bean
RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setDefaultSerializer(new StringRedisSerializer());
return redisTemplate;
}
@Bean
public RedisCacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
RedisCacheManager cacheManager = new CustomizeRedis(redisTemplate);
cacheManager.setUsePrefix(false);
//设置默认的过期时间,单位秒
cacheManager.setDefaultExpiration(60);
// 还可以使用下面的方法为指定的key设定过期时间,它将会在computeExpiration方法中用到
// Map<String, Long> expires = new HashMap<>();
// expires.put("cacheNameKey", 20L);
// expires.put("myKey", 40L);
// cacheManager.setExpires(expires);
return cacheManager;
}