https://blog.csdn.net/weixin_44488164/article/details/89479170
常见的如分页查询:使用单引号指定分割符,最终会拼接为一个字符串
@Cacheable(key = "#page+'-'+#pageSize")
当然还可以使用单引号自定义字符串作为缓存的key值
@Cacheable(key = "'countUsers'")
在redis中效果值如图
---------------------------------------------------------
详细讲解
https://www.jianshu.com/p/931484bb3fdc
对上述代码稍加改写,更适合自己
cache:
defaultCache:
expireTime: 200
userCacheList:
- cacheName: xxxxx
expireTime: 1800
- cacheName: xxxxxxx
expireTime: 1800
- cacheName: xxxxxxxxxx
expireTime: 30
- cacheName: xxxxxxxxxxxxxxxx
expireTime: 180000
@Data @Configuration @ConfigurationProperties(prefix = "cache") public class CacheConfig { /** * The User cache list. */ List<CacheExpireConfig> userCacheList; /** * The Default cache. */ CacheExpireConfig defaultCache; /** * The type Cache expire config. */ @Data public static class CacheExpireConfig { /** * The Cache name. */ String cacheName; /** * The Expire time. */ Long expireTime; } }
/** * The type Redis cache config. */ @Configuration public class RedisCacheConfig { /** * The Cache config. */ @Autowired CacheConfig cacheConfig; /** * 缓存管理器 * * @param lettuceConnectionFactory the lettuce connection factory * @return cache manager */ @Bean public CacheManager cacheManager(RedisConnectionFactory lettuceConnectionFactory) { // 对每个缓存空间应用不同的配置 Set<String> cacheNames = new HashSet<>(); Map<String, RedisCacheConfiguration> initCacheConfigMap = new HashMap<>(); List<CacheConfig.CacheExpireConfig> userCacheList = cacheConfig.getUserCacheList(); for (CacheConfig.CacheExpireConfig userCache : userCacheList) { cacheNames.add(userCache.getCacheName()); RedisCacheConfiguration userConfig = getDefaultRedisCacheConfiguration() .entryTtl(Duration.ofSeconds(userCache.getExpireTime())); initCacheConfigMap.put(userCache.getCacheName(), userConfig); } RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory) .cacheDefaults(getDefaultRedisCacheConfiguration()) .initialCacheNames(cacheNames) .withInitialCacheConfigurations(initCacheConfigMap) .build(); return cacheManager; } private RedisCacheConfiguration getDefaultRedisCacheConfiguration() { RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig(); // 设置缓存管理器管理的缓存的默认过期时间 defaultCacheConfig = defaultCacheConfig.entryTtl(Duration.ofSeconds(cacheConfig.getDefaultCache().getExpireTime())) // 设置 key为string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置value为json序列化 //.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new ProtostuffRedisSerializer())) // 不缓存空值 //.disableCachingNullValues() ; return defaultCacheConfig; } }