概述
Spring 3.1 引入了激动人心的基于凝视(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(比如EHCache 或者 OSCache),而是一个对缓存使用的抽象,通过在既有代码中加入少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。
Spring 的缓存技术还具备相当的灵活性。不仅能够使用 SpEL(Spring Expression Language)来定义缓存的 key 和各种 condition,还提供开箱即用的缓存暂时存储方案,也支持和主流的专业缓存比如 EHCache 集成。
其特点总结例如以下:
通过少量的配置 annotation 凝视就可以使得既有代码支持缓存
支持开箱即用 Out-Of-The-Box,即不用安装和部署额外第三方组件就可以使用缓存
支持 Spring Express Language,能使用对象的不论什么属性或者方法来定义缓存的 key 和 condition
支持 AspectJ,并通过事实上现不论什么方法的缓存支持
支持自己定义 key 和自己定义缓存管理者,具有相当的灵活性和扩展性
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.*;
@Component
@Slf4j
public class MetadataCacheRepository {
@Autowired
private MetadataProxy metadataProxy;
//查询缓存方法,如果缓存里没有,走DB查询
@Cacheable(value = "MATERIALDEFAULTPLANT", cacheManager = "concurrentMapCacheManager", key = "'MATERIALDEFAULTPLANT'+#materialCode+'_'+#legalPersonCode", unless = "!#result.isSuccess()")
public ResultVO<String> queryDefaultPlantByMaterialCode(String materialCode, String legalPersonCode){
return metadataProxy.queryDefaultPlantByMaterialCode(materialCode, legalPersonCode);
}
//删除缓存
@CacheEvict(value = "MATERIALDEFAULTPLANT", cacheManager = "concurrentMapCacheManager", key = "'MATERIALDEFAULTPLANT'+#materialCode+'_'+#legalPersonCode")
public void deleteQueryDefaultPlantByMaterialCode(String materialCode, String legalPersonCode){
return;
}
package xxxxxxx;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class CacheConfig {
@Bean("concurrentMapCacheManager")
public GuavaCacheManager concurrentMapCacheManager() {
GuavaCacheManager cacheManager = new GuavaCacheManager();
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.DAYS);//自动每一天后失效
cacheManager.setCacheBuilder(cacheBuilder);
return cacheManager;
}
}