shiro-ehcache maven 坐标
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
核心代码
EhCacheManager 配置 这里的 bt 是 ehcache-shiro.xml 文件 ehcache 节点 name
@Bean
public EhCacheManager getEhCacheManager()
{
net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("bt");
EhCacheManager em = new EhCacheManager();
if (StringUtils.isNull(cacheManager))
{
em.setCacheManager(new net.sf.ehcache.CacheManager(getCacheManagerConfigFileInputStream()));
return em;
}
else
{
em.setCacheManager(cacheManager);
return em;
}
}
protected InputStream getCacheManagerConfigFileInputStream()
{
String configFile = "classpath:ehcache/ehcache-shiro.xml";
InputStream inputStream = null;
try
{
inputStream = ResourceUtils.getInputStreamForPath(configFile);
byte[] b = IOUtils.toByteArray(inputStream);
InputStream in = new ByteArrayInputStream(b);
return in;
}
catch (IOException e)
{
throw new ConfigurationException(
"Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]", e);
}
finally
{
IOUtils.closeQuietly(inputStream);
}
}
ehcache-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="bt" updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600"
overflowToDisk="false">
</defaultCache>
<cache name="babanCache"
maxElementsInMemory="100000"
overflowToDisk="true"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
diskPersistent="true"
maxEntriesLocalHeap="2000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</cache>
</ehcache>
添加缓存
@Service
@Aspect
public class BabanAipCache {
private static final Logger logger = LoggerFactory.getLogger(BabanAipCache.class);
@Autowired
private CacheManager cacheManager;
private Cache<String,Object> cache;
@PostConstruct
public void init(){
cache = cacheManager.getCache("babanCache");
}
private static HashMap<String, Class> map = new HashMap<String, Class>() {
{
put("java.lang.Integer", Integer.class);
put("java.lang.Double", Double.class);
put("java.lang.Float", Float.class);
put("java.lang.Long", Long.class);
put("java.lang.Short", Short.class);
put("java.lang.Boolean", Boolean.class);
put("java.lang.Char", Char.class);
put("java.lang.String", String.class);
}
};
@Around("execution(* com.bt.web.controller.api.*.*(..))")
public Object getCache(ProceedingJoinPoint joinPoint){
try {
String target = joinPoint.getTarget().toString();
String className = target.split("@")[0];
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
HashMap<String, Object> paramMap = null;
if(args.length > 0){
Class<?>[] classes = new Class[args.length];
for (int k = 0; k < args.length; k++) {
if (!args[k].getClass().isPrimitive()) {
classes[k] = args[k].getClass();
}
}
ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
Method method = Class.forName(className).getMethod(methodName, classes);
String[] parameterNames = pnd.getParameterNames(method);
paramMap = new HashMap();
for (int i = 0; i < parameterNames.length; i++) {
paramMap.put(parameterNames[i], args[i]);
}
}
String cacheKey = ":" + className + "." + methodName+"_"+ (paramMap != null ? JSON.marshal(paramMap) : "");
Object cache = this.cache.get(cacheKey);
if(cache != null){
logger.info("缓存中获取,cacheKey={},cache={}",cacheKey,cache);
return cache;
}
Object obj = joinPoint.proceed();
this.cache.put(cacheKey,obj);
logger.info("存入缓存,cacheKey={},cache={}",cacheKey,obj);
return obj;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
清除缓存
@Aspect
@Service
public class BabanClearCache {
private static final Logger logger = LoggerFactory.getLogger(BabanAipCache.class);
@Autowired
private CacheManager cacheManager;
private Cache<String,Object> cache;
@PostConstruct
public void init(){
cache = cacheManager.getCache("babanCache");
}
@After("execution(* com.bt.web.controller.baban.*.addSave(..)) || " +
"execution(* com.bt.web.controller.baban.*.editSave(..)) || " +
"execution(* com.bt.web.controller.baban.*.remove(..))")
public void clearCache(){
this.cache.clear();
}
}