1 子定义配置redis缓存管理器
/**
* 自定义redis配置管理器
* @author leell
* @date 2023/10/30 14:50:53
*/
@Slf4j
public class RedisConfigCacheManager extends RedisCacheManager {
public RedisConfigCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
super(cacheWriter, defaultCacheConfiguration);
}
private static final RedisSerializationContext.SerializationPair<Object> DEFAULT_PAIR = RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer());
private static final CacheKeyPrefix DEFAULT_CACHE_KEY_PREFIX = cacheName -> cacheName+":";
@Override
protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
//redis name定义形式: 用户信息60s user:info#60
final int lastIndexOf = StringUtils.lastIndexOf(name, '#');
if (lastIndexOf > -1) {
final String ttl = StringUtils.substring(name, lastIndexOf + 1);
final Duration duration = Duration.ofSeconds(Long.parseLong(ttl));
cacheConfig = cacheConfig.entryTtl(duration);
//修改缓存key和value值的序列化方式
cacheConfig = cacheConfig.computePrefixWith(DEFAULT_CACHE_KEY_PREFIX)
.serializeValuesWith(DEFAULT_PAIR);
final String cacheName = StringUtils.substring(name, 0, lastIndexOf);
return super.createRedisCache(cacheName, cacheConfig);
}else{
//修改缓存key和value值的序列化方式
cacheConfig = cacheConfig.computePrefixWith(DEFAULT_CACHE_KEY_PREFIX)
.serializeValuesWith(DEFAULT_PAIR);
return super.createRedisCache(name, cacheConfig);
}
}
}
2 将redis 管理器加入spring管理,并且开启缓存
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory,Jackson2JsonRedisSerializer jackson2JsonRedisSerializer) {
ObjectMapper om = new ObjectMapper();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
// 解决查询缓存转换异常的问题
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMillis(-1))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
return new RedisConfigCacheManager(cacheWriter, config);
}
}
3 配置yaml,指定缓存类型
spring:
cache:
type: redis
4 使用案例
@Cacheable(cacheNames = "category:posts#10",key = "#categoryId.toString().concat('-').concat(#limitCount.toString())")
@Override
public List<Posts> listCategoryPosts(Long categoryId, Integer limitCount) {
List<Long> categoryIds = categoryService.listWithSubIds(categoryId);
return baseMapper.listPostsByCid(categoryIds, null, limitCount);
}