概述
1:CacheManager - 负责所有缓存的主要管理组件,它返回Cache 实例
2:Cache - 维护key/value 对
3:CacheManagerAware - 通过想要接收和使用CacheManager 实例的组件来实现
cacheManager = org.apache.shiro.cache.ehcache.EhcacheManager
securityManager.cacheManager = $cacheManager
<cache name="shiro-activeSessionCache"
maxElementsInMemory="10000"
overflowToDisk="true"
eternal="true"
timeToLiveSeconds="0"
timeToIdleSeconds="0"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="600"/>
包装使用其他的Cache框架
public class MyCacheManager implements CacheManager {
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
org.springframework.cache.Cache springCache = cacheManager.getCache(name);
return new SpringCacheWrapper(springCache);
}
class SpringCacheWrapper implements Cache {
private org.springframework.cache.Cache springCache;
SpringCacheWrapper(org.springframework.cache.Cache springCache) {
this.springCache = springCache;
}
public Object get(Object key) throws CacheException {
Object value = springCache.get(key);
if (value instanceof SimpleValueWrapper) {
return ((SimpleValueWrapper) value).get();
}
return value;
}
//等等,还有几个需要实现的方法,都可以使用你要使用的缓存框架去实现
}
}
缓存数据同步更新的解决方案
1:如果你使用的Spring,而且是自定义的Realm,那么可以在你的Realm里面添加一个方法来删除该用户的缓存数据,这样下次shiro在验证这个用户的时候,就会重新去获取数据,从而实现数据的同步
2:由于是自定义的Realm,可以把该对象作为Spring的bean,注入到你的业务对象中,在需要的时候就可以调用该方法来删除shiro的缓存数据了
public void removeUserCache(String userId){
SimplePrincipalCollection pc = new SimplePrincipalCollection();
pc.add(userId, super.getName());
super.clearCachedAuthorizationInfo(pc);
}
1:要注入MyRealm,但注意需要使用getter/setter来注入
2:在main方法中,示例如下:
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloAnno t = (HelloAnno)ctx.getBean("helloAnno");
t.login();
t.t();
t.t();
t.getMr().removeUserCache("javass");
t.t();
}