【SpringBoot】SpringSession的精致解析与实
本地安装并运行Redis
安装Redis:
brew install redis
启动Redis
redis-server /usr/local/etc/redis.conf
检测Redis是否正常运行,若返回PONG表示正常
redis-cli ping
Redis正常运行
通过Spring Initializr构建Spring Boot项目。
- 对应的Maven依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
顺便提一句,在参考网上其他SpringSession文档的时候,对于依赖中并没有提security-web,但是如果缺少这个依赖,会出现:
Caused by: java.lang.NoClassDefFoundError: org/springframework/security/web/authentication/RememberMeServices
- 配置application.properties
#服务端口
server.port=8080
#redi主机地址
spring.redis.host=localhost
#redis服务端口
spring.redis.port=6379
# spring session使用存储类型,spirngboot默认就是使用redis方式,如果不想用可以填none。
spring.session.store-type=redis
Redis集成SpringSession
首先我们创建一个配置类Config.class,然后使用注解@EnableRedisHttpSession来修饰这个类。
@EnableRedisHttpSession
public class Config {
}
注解@EnableRedisHttpSession的作用在官方文档,或者直接查看注解定义就可以看到:
The @EnableRedisHttpSession annotation creates a Spring Bean with the name of springSessionRepositoryFilter that implements Filter. The filter is in charge of replacing the HttpSession implementation to be backed by Spring Session. In this instance, Spring Session is backed by Redis.
它的意思是,当我们使用@EnableRedisHttpSession注解后,Spring会创建一个叫做SpringSessionRepositoryFilter,这个过滤器的作用是用来把servelet中原有的Http Session替换成Spring Session,在此Spring Session时基于Redis来实现。
Redis和Spring Session的集成到此为止,可见是极为方便,现在我们看一下实际的效果,创建Controller:
@RequestMapping("/test/cookie")
public String cookie(@RequestParam("browser") String browser, HttpServletRequest request, HttpSession httpSession) {
Object sessionBrowser = httpSession.getAttribute("browser");
if (sessionBrowser == null) {
System.out.println("不存在session,设置browser= " + browser);
httpSession.setAttribute("browser", browser);
} else {
System.out.println("存在session,browser= " + sessionBrowser.toString());
}
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + ":" + cookie.getValue());
}
}
return "OK";
}
在运行代码之前,先看一下Redis中的情况,在terminal中执行:
redis-cli //进入redis
keys *
空
当我们第一次访问Controller中的api时:http://localhost:8080/test/cookie?browser=chrome
打印日志:“不存在session,设置browser= chrome”,此时session信息也一并写入Redis: