springBoot+shiro缓存session
时间: 2025-06-29 18:07:06 浏览: 9
### 实现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]。
阅读全文
相关推荐

















