springboot + shiro 设置session过期时间

本文介绍在SpringBoot结合Shiro框架中如何有效管理会话,包括配置session过期时间的方法。通过在application.yml文件及Shiro的sessionManager中设置过期时间,解决外部tomcat环境下session管理问题。

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

在springboot + shiro中,可以设置session过期时间。有两种方式:

  1. 在application.yml 中设置过期时间,但是在使用外部tomcat的时候不起作用
    server:
      connection-timeout:
      servlet:
        session:
          timeout:

    在这里,设置了两座过期时间,您试一下,可能我这里是哪里不对。

  2. 因为使用shiro,那么就在shiro的sessionManager中设置过期时间

    @Bean
        public DefaultWebSessionManager getWebSessionManager(){
            DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();
            defaultWebSessionManager.setGlobalSessionTimeout(10000L);
            return defaultWebSessionManager;
        }

    这里有个问题,我见过期时间设置的是30m,所以,我就用了一个60s来替换,不行。改为了10000L这样表示,失效时间为10秒。就可以了

### 实现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]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值