这篇文章介绍一下在springboot项目中整合Spring Session,将session会话信息保存到Redis中,防止重启应用导致会话丢失。
第一步
创建一个springboot项目,添加spring-session-redis的依赖,因为要用到reids,所以要把redis相关依赖也加进来。
XML
<dependencies>
<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.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
第二步
在spplication.yml中配置命名空间和redis的连接信息。
XML
spring:
session:
redis:
save-mode: on_set_attribute
namespace: spring:session
redis:
host: localhost
port: 6379
database: 0
password: mhxy1218
第三步
在启动类上添加@EnableRedisHttpSession注解。
第四步
在项目中使用HttpSession,创建一个控制器类,然后添加两个接口分别用于设置和获取session。
java
package cn.edu.sgu.www.session.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
/**
* @author heyunlin
* @version 1.0
*/
@RestController
@RequestMapping("/session")
public class SessionController {
@GetMapping("/getSession")
public String getSession(HttpSession session, HttpServletRequest request) {
Object name = session.getAttribute("name");
// 查看请求头
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String element = headerNames.nextElement();
System.out.println(element);
}
return name.toString();
}
@GetMapping("/setSession")
public void setSession(HttpSession session, String name) {
session.setAttribute("name", name);
}
}
第四步
启动项目,在浏览器输入以下网址,设置name为沐雨橙风ιε
java
http://localhost:8080/session/setSession?name=%E6%B2%90%E9%9B%A8%E6%A9%99%E9%A3%8E%CE%B9%CE%B5
然后,再访问获取session的接口
java
http://localhost:8080/session/getSession
第五步
查看浏览器cookie,按F12打开浏览器控制台,点击网络查看刚刚发起的请求携带的cookile数据。

把这长串字符串复制出来
第六步
清空浏览器,访问获取session数据的接口。
这时候发现已经获取不到了,这是因为清理缓存会把浏览器的cookie数据删除,所以请求时没有携带cookile请求头。

第七步
通过postman访问/session/getSession,携带请求头cookie,其内容为
SESSION=ZDcyNGFlNzgtYzUyYS00NGFjLTkwYzgtMzRiYWNjNjE1Y2Y0

第八步
重启项目,然后再获取session,这时候数据还在~

好了,文章就分享到这里了,代码已经上传到gitee~
spring boot整合spring-session-redis案例项目https://gitee.com/muyu-chengfeng/spring-session-redis.git