文章目录
- Session持久化
- 1. 添加依赖
- 2. 配置redis连接信息
- 3. 存储和读取session从Redis
Session持久化
1. 添加依赖
在项目中添加session依赖和redis依赖,如下所示:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId></dependency>
2. 配置redis连接信息
# redis连接配置信息
spring.redis.host=124.221.76.124
# 不写默认wei6379,数据库为0
# spring.redis.database=15
spring.redis.port=6379# 配置session连接信息
spring.session.store-type=redis
server.servlet.session.timeout=1800
spring.session.redis.flush-mode=on_save
spring.session.redis.namespace=spring:session
3. 存储和读取session从Redis
package com.example.sp_redis.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;/*** 实现session持久化* @author zq* @date 2023-07-26 14:37*/@RestController
public class UserController {private static final String SESS_USER_KEY = "SESS_USER_KEY";@RequestMapping("/login")public String login(HttpSession httpSession) {//存入sessionhttpSession.setAttribute(SESS_USER_KEY, "wangwu");return "Session set success.";}@RequestMapping("/getuser")public String getUser(HttpServletRequest request) {String user = "NULL";HttpSession session = request.getSession(false);if (session != null) {//从redis中获取sessionObject userObj = session.getAttribute(SESS_USER_KEY);if (userObj != null) {user = userObj.toString();}}return user;}
}
我们访问localhost:8080/login 将session存入redis
接着访问localhost:8080/login可以读取到缓存中的数据
接着我们可以在redis客户端看到存入到session