shiro缓存机实例代码

2019-01-16 23:10:43于丽

Shiro提供了类似于Spring的Cache抽象,即Shiro本身不实现Cache,但是对Cache进行了又抽象,方便更换不同的底层Cache实现。 

Shiro提供的Cache接口: 

Java代码  

public interface Cache<K, V> { //根据Key获取缓存中的值 public V get(K key) throws CacheException; //往缓存中放入key-value,返回缓存中之前的值 public V put(K key, V value) throws CacheException; //移除缓存中key对应的值,返回该值 public V remove(K key) throws CacheException; //清空整个缓存 public void clear() throws CacheException; //返回缓存大小 public int size(); //获取缓存中所有的key public Set<K> keys(); //获取缓存中所有的value public Collection<V> values(); }

Shiro提供的CacheManager接口: 

Java代码 


public interface CacheManager { //根据缓存名字获取一个Cache public <K, V> Cache<K, V> getCache(String name) throws CacheException; }

Shiro还提供了CacheManagerAware用于注入CacheManager: 

Java代码  

public interface CacheManagerAware { //注入CacheManager void setCacheManager(CacheManager cacheManager); }

Shiro内部相应的组件(DefaultSecurityManager)会自动检测相应的对象(如Realm)是否实现了CacheManagerAware并自动注入相应的CacheManager。  

Realm缓存

Shiro提供了CachingRealm,其实现了CacheManagerAware接口,提供了缓存的一些基础实现;另外AuthenticatingRealm及AuthorizingRealm分别提供了对AuthenticationInfo 和AuthorizationInfo信息的缓存。 

ini配置   

Java代码  

userRealm=com.github.zhangkaitao.shiro.chapter11.realm.UserRealm userRealm.credentialsMatcher=$credentialsMatcher userRealm.cachingEnabled=true userRealm.authenticationCachingEnabled=true userRealm.authenticationCacheName=authenticationCache userRealm.authorizationCachingEnabled=true userRealm.authorizationCacheName=authorizationCache securityManager.realms=$userRealm cacheManager=org.apache.shiro.cache.ehcache.EhCacheManager cacheManager.cacheManagerConfigFile=classpath:shiro-ehcache.xml securityManager.cacheManager=$cacheManager

userRealm.cachingEnabled:启用缓存,默认false;
userRealm.authenticationCachingEnabled:启用身份验证缓存,即缓存AuthenticationInfo信息,默认false;
userRealm.authenticationCacheName:缓存AuthenticationInfo信息的缓存名称;
userRealm. authorizationCachingEnabled:启用授权缓存,即缓存AuthorizationInfo信息,默认false;
userRealm. authorizationCacheName:缓存AuthorizationInfo信息的缓存名称;

cacheManager:缓存管理器,此处使用EhCacheManager,即Ehcache实现,需要导入相应的Ehcache依赖,请参考pom.xml;