企业如何通过vue小程序开发满足高效运营与合规性需求
828
2023-01-24
详解SpringBoot2.0的@Cacheable(Redis)缓存失效时间解决方案
问题
@Cacheable注解不支持配置过期时间,所有需要通过配置CacheManneg来配置默认的过期时间和针对每个类或者是方法进行缓存失效时间配置。
解决
可以采用如下的配置信息来解决的设置失效时间问题
配置信息
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl(30*60), // 默认策略,未配置的 key 会使用这个
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
private Map
Map
//SsoCache和BasicDataCache进行过期时间配置
redisCacheConfigurationMap.put("SsoCache", this.getRedisCacheConfigurationWithTtl(24*60*60));
redisCacheConfigurationMap.put("BasicDataCache", this.getRedisCacheConfigurationWithTtl(30*60));
return redisCacheConfiguratGOswrdzRcionMap;
}
private RedisCacheConfiguration getRhttp://edisCacheConfigurationWithTtl(Integer seconds) {
Jackson2jsonRedisSerializer
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
return redisCacheConfiguration;
}
@Bean
public KeyGenerator wiselyKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append("." + method.getName());
if(params==null||params.length==0||params[0]==null){
return null;
}
String join = String.join("&", Arrays.stream(params).map(Object::toString).collect(Collectors.toList()));
String format = String.format("%s{%s}", sb.toString(), join);
//log.info("缓存key:" + format);
return format;
}
};
}
使用方式
@CacheConfig(cacheNames = "SsoCache")
public class SsoCache{
@Cacheable(keyGenerator = "wiselyKeyGenerator")
public String getTokenByGsid(String gsid)
}
//二者选其一,可以使用value上的信息,来替换类上cacheNames的信GOswrdzRc息
@Cacheable(value = "BasicDataCache",keyGenerator = "wiselyKeyGenerator")
public String getTokenByGsid(String gsid)
效果展示
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~