一、说明
1、查询增加缓存,使用@Cacheable注解
2、项目中已经用到了ehcache,现在需求是两个都用
二、备份配置
1、redisConfig增加代码
@Bean("redisCacheManage")
@Primary
public CacheManager redisCacheManager(RedisConnectionFactory factory) {
Map<String, RedisCacheConfiguration> configurationMap = MapUtil.newHashMap();
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.disableCachingNullValues();
return RedisCacheManager.builder(factory)
.initialCacheNames(configurationMap.keySet())
.withInitialCacheConfigurations(configurationMap)
.cacheDefaults(config)
.build();
}
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
private RedisSerializer<Object> valueSerializer() {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 此项必须配置,否则如果序列化的对象里边还有对象,会报如下错误:
// java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX
objectMapper.activateDefaultTyping(
objectMapper.getPolymorphicTypeValidator(),
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.PROPERTY);
// 旧版写法:
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
return jackson2JsonRedisSerializer;
}
2、直接使用
1)缓存
@Cacheable(key ="'method_' + #tenantId + '_' + #bo.toString()", unless = "#result == null", cacheManager = "redisCacheManage", cacheNames = "api")
说明1:cacheNames其实是个前缀,也可以理解成分组的概念;方便手动删除时,根据前缀删除
2)示例截图
3)redis存储结果截图
~~