新版本配置
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
return (builder) -> {
for (Map.Entry<String, Duration> entry : RedisCacheName.getCacheMap().entrySet()) {
builder.withCacheConfiguration(entry.getKey(),
RedisCacheConfiguration.defaultCacheConfig().entryTtl(entry.getValue()));
}
};
}
public static class RedisCacheName {
public static final String CACHE_10MIN = "CACHE_10MIN";
@Getter
private static final Map<String, Duration> cacheMap;
static {
cacheMap = ImmutableMap.<String, Duration>builder().put(CACHE_10MIN, Duration.ofSeconds(10L)).build();
}
}
}
老版本配置
interface CacheNames{
String CACHE_15MINS = "sssss:cache:15m";
/** 30分钟缓存组 */
String CACHE_30MINS = "sssss:cache:30m";
/** 60分钟缓存组 */
String CACHE_60MINS = "sssss:cache:60m";
/** 180分钟缓存组 */
String CACHE_180MINS = "sssss:cache:180m";
}
@Component
public class RedisCacheCustomizer
implements CacheManagerCustomizer<RedisCacheManager> {
/** CacheManager缓存自定义初始化比较早,尽量不要@autowired 其他spring 组件 */
@Override
public void customize(RedisCacheManager cacheManager) {
// 自定义缓存名对应的过期时间
Map<String, Long> expires = ImmutableMap.<String, Long>builder()
.put(CacheNames.CACHE_15MINS, TimeUnit.MINUTES.toSeconds(15))
.put(CacheNames.CACHE_30MINS, TimeUnit.MINUTES.toSeconds(30))
.put(CacheNames.CACHE_60MINS, TimeUnit.MINUTES.toSeconds(60))
.put(CacheNames.CACHE_180MINS, TimeUnit.MINUTES.toSeconds(180)).build();
// spring cache是根据cache name查找缓存过期时长的,如果找不到,则使用默认值
cacheManager.setDefaultExpiration(TimeUnit.MINUTES.toSeconds(30));
cacheManager.setExpires(expires);
}
}
@Cacheable(key = "key", cacheNames = CacheNames.CACHE_15MINS)
public String demo2(String key) {
return "abc" + key;
}