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) {
//存入session
httpSession.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中获取session
Object userObj = session.getAttribute(SESS_USER_KEY);
if (userObj != null) {
user = userObj.toString();
}
}
return user;
}
}
我们访问localhost:8080/login 将session存入redis
接着访问localhost:8080/login可以读取到缓存中的数据
接着我们可以在redis客户端看到存入到session文章来源:https://www.toymoban.com/news/detail-609643.html
文章来源地址https://www.toymoban.com/news/detail-609643.html
到了这里,关于将Spring Session存储到Redis中实现持久化的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!