使用mvc环境,spring-data-redis所需jar包版本如下,版本不同会报包冲突:
spring4.2.8
spring-data-redis-1.7.4
spring-data-commons-1.12.4
jedis-2.9.0 --依赖commons-lang3-3.3.2
通过shiro管理session,将session缓存到redis数据库,可以实现在应用集群下session共享。
首先配置spring-context-shiro.xml,这里引用jeesite配置进行修改,重点关注session缓存配置
使用mvc环境,spring-data-redis所需jar包版本如下,版本不同会报包冲突:
spring4.2.8
spring-data-redis-1.7.4
spring-data-commons-1.12.4
jedis-2.9.0 --依赖commons-lang3-3.3.2
通过shiro管理session,将session缓存到redis数据库,可以实现在应用集群下session共享。
配置spring-context-shiro.xml,这里引用jeesite配置进行修改,重点关注session缓存配置
Shiro Configuration
/static/** = anon
/userfiles/** = anon
${frontPath} = anon
${frontPath}/** = anon
${adminPath}/cas = cas
${adminPath}/login = authc
${adminPath}/logout = logout
${adminPath}/** = user
/act/editor/** = user
/ReportServer/** = user
RedisCacheSessionDao--
redis Session存储容器
package com.thinkgem.jeesite.common.security.shiro.session;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import com.thinkgem.jeesite.common.security.shiro.CollectionSerializer;
public class RedisCacheSessionDao extends AbstractSessionDAO implements SessionDAO{
private static Logger logger = LoggerFactory.getLogger(RedisCacheSessionDao.class);
@Autowired
private RedisTemplate redisTemplate;
@Value("${redis.keyPrefix}")
private String redisPrefixKey;
/**
* The Redis key prefix for the sessions
*/
private String sessionKeyPrefix = "shiro_session_";
private String getKey(String originalKey) {
return redisPrefixKey + sessionKeyPrefix+originalKey;
}
@PostConstruct
public void init(){
logger.info("注入催收的序列/反序列类");
CollectionSerializer collectionSerializer=CollectionSerializer.getInstance();
redisTemplate.setDefaultSerializer(collectionSerializer);
//redisTemplate默认采用的其实是valueSerializer,就算是采用其他ops也一样,这是一个坑。
redisTemplate.setValueSerializer(collectionSerializer);
}
@Override
public void update(Session session) throws UnknownSessionException {
logger.debug("更新seesion,id=[{}]", session.getId().toString());
try {
redisTemplate.opsForValue().set(getKey(session.getId().toString()), session,30,TimeUnit.MINUTES);
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
}
@Override
public void delete(Session session) {
logger.debug("删除seesion,id=[{}]", session.getId().toString());
try {
String key=getKey(session.getId().toString());
redisTemplate.delete(key);
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
}
@Override
public Collection getActiveSessions() {
logger.info("获取存活的session");
return Collections.emptySet();
}
@Override
protected Serializable doCreate(Session session) {
Serializable sessionId = generateSessionId(session);
assignSessionId(session, sessionId);
logger.debug("创建seesion,id=[{}]", session.getId().toString());
try {
redisTemplate.opsForValue().set(getKey(session.getId().toString()), session,30,TimeUnit.MINUTES);
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return sessionId;
}
@Override
protected Session doReadSession(Serializable sessionId) {
logger.debug("获取seesion,id=[{}]", sessionId.toString());
Session readSession = null;
try {
readSession=(Session) redisTemplate.opsForValue().get(getKey(sessionId.toString()));
} catch (Exception e) {
logger.error(e.getMessage());
}
return readSession;
}
@Override
public Collection getActiveSessions(boolean includeLeave) {
return Collections.emptySet();
}
@Override
public Collection getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
return getActiveSessions(includeLeave, null, null);
}
}
RedisCacheManager--redis 缓存管理器
public class RedisCacheManager implements CacheManager {
@Resource
private RedisTemplate redisTemplate;
@Override
public Cache getCache(String name) throws CacheException {
return new ShiroCache(name, redisTemplate);
}
public RedisTemplate getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
}
shiroCache
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
@SuppressWarnings("unchecked")
public class ShiroCache implements Cache {
private static final String REDIS_SHIRO_CACHE = "weiyou-shiro-cache:";
private String cacheKey;
private RedisTemplate redisTemplate;
private long globExpire = 30;
@SuppressWarnings("rawtypes")
public ShiroCache(String name, RedisTemplate client) {
this.cacheKey = REDIS_SHIRO_CACHE + name + ":";
this.redisTemplate = client;
}
@Override
public V get(K key) throws CacheException {
Boolean exsite = redisTemplate.hasKey(getCacheKey(key));
if(!exsite){
return null;
}
redisTemplate.boundValueOps(getCacheKey(key)).expire(globExpire, TimeUnit.MINUTES);
return redisTemplate.boundValueOps(getCacheKey(key)).get();
}
@Override
public V put(K key, V value) throws CacheException {
V old = get(key);
redisTemplate.boundValueOps(getCacheKey(key)).set(value);
return old;
}
@Override
public V remove(K key) throws CacheException {
V old = get(key);
redisTemplate.delete(getCacheKey(key));
return old;
}
@Override
public void clear() throws CacheException {
redisTemplate.delete(keys());
}
@Override
public int size() {
return keys().size();
}
@Override
public Set keys() {
return redisTemplate.keys(getCacheKey("*"));
}
@Override
public Collection values() {
Set set = keys();
List list = new ArrayList<>();
for (K s : set) {
list.add(get(s));
}
return list;
}
private K getCacheKey(Object k) {
return (K) (this.cacheKey + k);
}
}
shiro框架首次访问缓存,先去执行get方法,没有返回为空。
再配置spring-context-shiro.xml文件
单个redis配置:
Jedis Configuration
redis集群配置:
Jedis Configuration
附:网上找来的redisTemplate工具类
package com.ryx.global.util;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
/**
* 基于spring和redis的redisTemplate工具类
* 针对所有的hash 都是以h开头的方法
* 针对所有的Set 都是以s开头的方法 不含通用方法
* 针对所有的List 都是以l开头的方法
*/
public class RedisUtil {
private RedisTemplate redisTemplate;
public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
//=============================common============================
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key,Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key 键
* @param by 要增加几(大于0)
* @return
*/
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param by 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map