【原创】大叔问题定位分享(35)spring中session失效时间

博客围绕spring项目中session过期问题展开。虽将sessionid对应cookie过期时间设得很长,但session半小时后仍失效。介绍了spring中session实现接口及两个实现类,单机和分布式环境分别使用不同类,还指出创建session时设置的两个时间决定过期判断,并给出设置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring项目中将sessionid对应的cookie过期时间设置很长,但是实际session还是在半个小时后失效,跟了一下代码,spring中session实现接口为

org.springframework.session.SessionRepository

public interface SessionRepository<S extends Session> {
    S createSession();

    void save(S var1);

    S findById(String var1);

    void deleteById(String var1);
}

这个接口有两个实现类:

MapSessionRepository
RedisOperationsSessionRepository

单机环境使用前者,分布式环境使用后者,来看后者代码:

org.springframework.session.data.redis.RedisOperationsSessionRepository

    public RedisOperationsSessionRepository.RedisSession createSession() {
        RedisOperationsSessionRepository.RedisSession redisSession = new RedisOperationsSessionRepository.RedisSession();
        if(this.defaultMaxInactiveInterval != null) {
            redisSession.setMaxInactiveInterval(Duration.ofSeconds((long)this.defaultMaxInactiveInterval.intValue()));
        }

        return redisSession;
    }

org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession

        RedisSession() {
            this(new MapSession());
            this.delta.put("creationTime", Long.valueOf(this.getCreationTime().toEpochMilli()));
            this.delta.put("maxInactiveInterval", Integer.valueOf((int)this.getMaxInactiveInterval().getSeconds()));
            this.delta.put("lastAccessedTime", Long.valueOf(this.getLastAccessedTime().toEpochMilli()));
            this.isNew = true;
            this.flushImmediateIfNecessary();
        }

        public boolean isExpired() {
            return this.cached.isExpired();
        }

org.springframework.session.MapSession

    public boolean isExpired() {
        return this.isExpired(Instant.now());
    }

    boolean isExpired(Instant now) {
        return this.maxInactiveInterval.isNegative()?false:now.minus(this.maxInactiveInterval).compareTo(this.lastAccessedTime) >= 0;
    }

 

可见是在创建session的时候设置两个时间,

lastAccessedTime
maxInactiveInterval

如果 当前时间 - maxInactiveInterval > lastAccessedTime 就会认为session过期,设置的方法:

@EnableRedisHttpSession(maxInactiveIntervalInSeconds=2000) 

 

转载于:https://www.cnblogs.com/barneywill/p/11163735.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值