Spring Cache 两个需求

  • 缓存失效时间支持在方法的注解上指定
    Spring Cache默认是不支持在@Cacheable上添加过期时间的,可以在配置缓存容器时统一指定:

@Beanpublic CacheManager cacheManager(        @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {    CustomizedRedisCacheManager cacheManager= new CustomizedRedisCacheManager(redisTemplate);
    cacheManager.setDefaultExpiration(60);    Map<String,Long> expiresMap=new HashMap<>();
    expiresMap.put("Product",5L);
    cacheManager.setExpires(expiresMap);    return cacheManager;
}

想这样配置过期时间,焦点在value的格式上Product#5#2,详情下面会详细说明。

    @Cacheable(value = {"Product#5#2"},key ="#id")

上面两种各有利弊,并不是说哪一种一定要比另外一种强,根据自己项目的实际情况选择。

    网友评论