文章目录
Shiro缓存管理
用于缓存角色数据和权限数据,每次不用都从数据库中获取数据,直接从缓存中获取
redis缓存操作
package com.shiro.cache;
import com.shiro.util.JedisUtil;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;
/**
* redis缓存操作
* @param <K>
* @param <V>
*/
@Component
public class RedisCache<K,V> implements Cache<K,V>{
@Resource
private JedisUtil jedisUtil;
private final String CACHE_PREFIX = "shiro-cache:";
/**
* 获取带前缀的key
* @param k
* @return
*/
private byte[] getKey(K k) {
if(k instanceof String) {
return (CACHE_PREFIX + k).getBytes();
}
return SerializationUtils.serialize(k);
}
/**
* 查
* @param k
* @return
* @throws CacheException
*/
@Override
public V get(K k) throws CacheException {
System.out.println("从Redis中获取角色/权限数据");
byte[] value = jedisUtil.get(getKey(k));
if(value != null) {
return (V) SerializationUtils.deserialize(value);
}
return null;
}
/**
* 增
* @param k
* @param v
* @return
* @throws CacheException
*/
@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;
}
/**
* 删
* @param k
* @return
* @throws CacheException
*/
@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;
}
/**
* 不要重写会将redis里面的数据全部清空
* @throws CacheException
*/
@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;
}
}
自定义shiro缓存
package com.shiro.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
/**
* shiro缓存
*/
public class RedisCacheManager implements CacheManager {
@Autowired
private RedisCache redisCache;
@Override
public <K, V> Cache<K, V> getCache(String s) throws CacheException {
return redisCache;
}
}
spring-shiro.xml
将自定义shiro授权(角色、权限)缓存RedisCacheManager注入到securityManager中
<!-- 创建SecurityManager对象 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--注入自定义Realm-->
<property name="realm" ref="realm" />
<!--注入自定义SessionManager-->
<property name="sessionManager" ref="sessionManager" />
<!--注入自定义shiro授权(角色、权限)缓存-->
<property name="cacheManager" ref="cacheManager" />
</bean>
<!--自定义shiro授权(角色、权限)缓存-->
<bean class="com.shiro.cache.RedisCacheManager" id="cacheManager"></bean>