spring boot shiro 登录redis共享sesson配置

本文介绍如何在Spring Boot应用中结合Shiro框架,利用Redis Sentinel集群实现用户登录session的共享,解决多服务器间session切换问题。
摘要由CSDN通过智能技术生成

 由于多台集群服务端导致登录用户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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值