Shiro缓存管理
- CacheManager、Cache
- Redis实现CacheManager
spring.xml
<!-- 创建SecurityManager对象-->
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
<property name="realm" ref="realm" />
<property name="sessionManager" ref="sessionManager" />
<property name="cacheManager" ref="cacheManager" />
</bean>
<bean class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager" id="sessionManager">
<property name="sessionDAO" ref="redisSessionDao" />
</bean>
<bean class="com.imooc.session.RedisSessionDao" id="redisSessionDao" />
<bean class="com.imooc.cache.RedisCacheManager" id="cacheManager" />
RedisCache
public class RedisCache<K, V> implements Cache<K, V> {
@Resource
private JedisUtil jedisUtil;
private final String CACHE_PREFIX = "imooc-cache";
private byte[] getKey(K k) {
if (k instanceof String) {
return (CACHE_PREFIX + k).getBytes();
}
return SerializationUtils.serialize(k);
}
@Override
public V get(K k) throws CacheException {
byte[] value= jedisUtil.get(getKey(k));
if (value != null) {
return (V) SerializationUtils.deserialize(value);
}
return null;
}
@Override
public V put(K k, V v) throws CacheException {
byte[] key = getKey(k);
byte[] value = SerializationUtils.serialize(v);
jedisUtil.set(key, value);
jedisUtil.expire(key, 600);
return v;
}
@Override
public V remove(K k) throws CacheException {
byte[] key = getKey(k);
byte[] value = jedisUtil.get(key);
jedisUtil.del(key);
if (value != null) {
return (V) SerializationUtils.deserialize(value);
}
return null;
}
@Override
public void clear() throws CacheException {
//
}
@Override
public int size() {
return 0;
}
@Override
public Set<K> keys() {
return null;
}
@Override
public Collection<V> values() {
return null;
}
}
RedisCacheManager
public class RedisCacheManager implements CacheManager {
@Resource
private RedisCache redisCache;
@Override
public <K, V> Cache<K, V> getCache(String s) throws CacheException {
return redisCache;
}
}