shiro 内置CacheManager
- MemoryConstrainedCacheManager (适用于单JVM生产环境的实现)
shiroCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $shiroCacheManager
- EhCacheManager (依赖ehcache)
shiroCacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
shiroCacheManager.cacheManagerConfigFile = classpath:ehcache-shiro.xml
securityManager.cacheManager = $shiroCacheManager
自定义RedisCacheManager 支持Redis缓存
public class RedisCacheManager implements CacheManager {
private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();
/*永不过期*/
private int expire = 0;
public int getExpire() {
return expire;
}
public void setExpire(int expire) {
this.expire = expire;
}
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
Cache c = caches.get(name);
if (c == null) {
c = new RedisCache<K, V>(expire);
caches.put(name, c);
}
return c;
}
}
RedisCache实现
public class RedisCache<K, V> implements org.apache.shiro.cache.Cache<K, V> {
private static String SHIRO_KEY = "shiro";
private int expire = 0;
public RedisCache(int expire) {
this.expire = expire;
}
public V get(K key) throws CacheException {
LogKit.debug("根据key从Redis中获取对象 key [" + key + "]");
if (key == null) {
return null;
} else {
return Redis.use().hget(SHIRO_KEY, key);
}
}
public V put(K key, V value) throws CacheException {
LogKit.debug("根据key从存储 key [" + key + "]");
Redis.use().hset(SHIRO_KEY, key, value);
Redis.use().expire(SHIRO_KEY, expire);
return value;
}
/**
* shiro 的默认删除KEY:用户的
*
* @throws CacheException CacheException
*/
public V remove(K key) throws CacheException {
LogKit.debug("从redis中删除 key [" + key + "]");
V previous = get(key);
return previous;
}
public void clear() throws CacheException {
LogKit.debug("从redis中删除所有元素");
try {
Redis.use().del(SHIRO_KEY);
} catch (Throwable t) {
throw new CacheException(t);
}
}
public int size() {
Long length = Redis.use().hlen(SHIRO_KEY);
return length.intValue();
}
public Set<K> keys() {
return (Set<K>) Redis.use().hkeys(SHIRO_KEY);
}
public Collection<V> values() {
return Redis.use().hvals(SHIRO_KEY);
}
}
使用方法
在ini文件中配置
shiroCacheManager = io.github.wx.common.shiro.cache.RedisCacheManager
shiroCacheManager.expire = 1800
securityManager.cacheManager = $shiroCacheManager
禁止转载