springboot shiro session过期时间配置

本文介绍两种设置Session过期时间的方法:一是通过内置Tomcat容器配置,适用于内部部署场景;二是利用Shiro框架进行配置,后者优先级更高。此外还提到了直接通过HttpServletRequest设置Session过期时间。

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

第一种方式:使用内置tomcat容器配置:

在application.properties配置:

#session过期时间(单位秒)  默认1800s(30min)
#设置小于60秒,则会默认取1分钟
#实际过期时间为秒数对分钟取整,比如设置2000,则 2000s/60=33min,33min*60=1980s,实际过期时间为1980s
server.session.timeout=3600

说明:该种方式只有使用内部tomcat时有效(EmbeddedServletContainerCustomizer原理是一样的,也是只有使用内部tomcat时有效),将工程打war包使用外部tomcat等容器是无效的。

第二种方式:使用shiro配置:

在shiro config中配置:

@Bean(name = "sessionManager")
public DefaultWebSessionManager sessionManager() {
	DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
	// 设置session过期时间3600s
	sessionManager.setGlobalSessionTimeout(3600000L);
	return sessionManager;
}

@Bean
public SecurityManager securityManager() {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    //securityManager.setRealm(shiroRealm());
    securityManager.setSessionManager(sessionManager());
    return securityManager;
}

其他方式

HttpServletRequest request.getSession().setMaxInactiveInterval(interval)

 if(SecurityUtils.getSubject()!=null) { 
        	SecurityUtils.getSubject().getSession().setTimeout(1800000L);
        }

测试:

System.out.println("Session过期时间"+request.getSession().getMaxInactiveInterval());
System.out.println("shiro-Session过期时间"+SecurityUtils.getSubject().getSession().getTimeout());

说明:上述2个值是一样的。配置shiro-Session的优先级高于使用servlet的session。

### 实现Spring Boot Shiro Session缓存 #### 使用Ehcache作为Session缓存机制 为了使Shiro能够利用Ehcache来存储会话数据,需先引入必要的依赖项到`pom.xml`文件中: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot-web-starter</artifactId> <version>${shiro.version}</version> </dependency> <!-- EhCache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>${ehcache.version}</version> </dependency> ``` 接着定义一个名为`ShiroEhcacheManager.java`的Java类用于初始化Ehcache实例并将其注册给Shiro环境。 ```java import org.apache.shiro.cache.CacheManager; import org.apache.shiro.cache.ehcache.EhCacheManager; @Configuration public class ShiroEhcacheManager { @Bean(name="cacheManager") public CacheManager getCacheManager(){ EhCacheManager em = new EhCacheManager(); em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); return em; } } ``` 上述代码片段展示了如何配置Ehcache成为默认的缓存提供者[^2]。注意这里指定了外部化的EHCache配置文件路径以便更灵活地调整缓存策略参数。 对于具体的Ehcache配置(`ehcache-shiro.xml`),可以根据实际需求定制化设置不同的缓存区域及其过期策略等特性。 --- #### 结合Redis实现分布式环境下的一致性Session管理 当应用程序部署于多节点集群架构下时,则推荐采用Redis替代本地内存或单机版Ehcache来进行跨服务器间共享同一份实时更新后的用户登录状态副本。此时除了继续保留原有的Shiro核心功能外还需要额外增加如下几处改动: 1. **添加Maven坐标** 同样编辑项目根目录下的`pom.xml`文档追加对lettuce驱动的支持以连接远程Redis服务端口监听地址; ```xml <!-- Redis Client Library --> <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> <version>${redis.version}</version> </dependency> <!-- Enable Spring Data Redis support --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. **编写自定义SessionDAO继承DefaultWebSessionDao** 创建一个新的子类重写其中部分方法从而允许我们将原本保存至JVM堆内的对象序列化后持久化入指定key-value store之中去。 ```java import java.io.Serializable; import javax.annotation.Resource; import org.apache.shiro.session.Session; import org.apache.shiro.session.mgt.ValidatingSession; import org.apache.shiro.session.mgt.eis.CachingSessionDAO; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.serializer.StringRedisSerializer; ... /** * Customized implementation of {@link CachingSessionDAO} that stores sessions into a distributed cache. */ public final class RedisSessionDAO extends AbstractValidatingSessionDAO implements Serializable { private static final long serialVersionUID = 793480567L; private String keyPrefix = "shiro_redis_session:"; ... protected void doUpdate(Session session){ // Update the corresponding entry within external storage system... } protected void doDelete(Session session){ // Remove expired entries from persistent layer accordingly... } protected Serializable getSessionId(Serializable sessionId, boolean create){ if (create && null == sessionId) { return generateNewSessionId(); } else { return sessionId; } } ... } ``` 3. **激活@EnableRedisHttpSession注解开关** 修改之前提到过的全局配置类使其具备感知HTTP请求上下文中携带cookie信息的能力进而完成自动续签操作防止频繁触发全量同步动作造成不必要的网络开销浪费现象发生。 ```java package com.example.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.ConfigureRedisAction; import org.springframework.session.web.http.CookieSerializer; import org.springframework.session.web.http.DefaultCookieSerializer; @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds=86400*30)//maxInactiveIntervalInSeconds: 设置Session失效时间 public class SessionConfig { @Bean ConfigureRedisAction configureRedisAction() { return ConfigureRedisAction.NO_OP; } @Bean CookieSerializer cookieSerializer() { DefaultCookieSerializer serializer = new DefaultCookieSerializer(); serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); return serializer; } } ``` 以上即是在Spring Boot应用里集成Apache Shiro框架并通过第三方中间件优化其内部工作流程的一些常见实践方案[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值