由于多台集群服务端导致登录用户session切换问题,使用redis哨兵模式共享shiro登录session;
用到的pom依赖
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>3.2.3</version>
</dependency>
/**
* @author rayen
*/
public class RedisSessionDao extends AbstractSessionDAO {
private static Logger logger = LoggerFactory.getLogger(RedisSessionDao.class);
private String keyPrefix = "SHIRO:SESSION:";
private long sessionInMemoryTimeout = 1000L;
private boolean sessionInMemoryEnabled = true;
private int expire = -2;
private IRedisManager redisManager;
private RedisSerializer keySerializer = new StringSerializer();
private RedisSerializer valueSerializer = new ObjectSerializer();
private static ThreadLocal sessionsInThread = new ThreadLocal();
private static int redisSessionExpireTime = 15*60*1000; // 设置session有效期15分钟
public RedisSessionDao() {
}
public void update(Session session) throws UnknownSessionException {
this.saveSession(session);
if (this.sessionInMemoryEnabled) {
this.setSessionToThreadLocal(session.getId(), session);
}
}
private void saveSession(Session session) throws UnknownSessionException {
if (session != null && session.getId() != null) {
session.setTimeout(redisSessionExpireTime);
byte[] key;
byte[] value;
try {
key = this.keySerializer.serialize(this.getRedisSessionKey(session.getId()));
value = this.valueSerializer.serialize(session);
} catch (SerializationException var5) {
logger.error("serialize session error. session id=" + session.getId());
throw new UnknownSessionException(var5);
}
if (this.expire == -2) {
this.redisManager.set(key, value, (int) (session.getTimeout() / 1000L));
} else {
if (this.expire != -1 && (long) (this.expire * 1000) < session.getTimeout()) {
logger.warn("Redis session