博客
关于我
Java常用包系列--SpringSession(实战)
阅读量:552 次
发布时间:2019-03-07

本文共 6669 字,大约阅读时间需要 22 分钟。

Spring Boot + Redis 会话管理实例

项目配置

Maven 依赖管理

基于 Spring Boot 的 Maven 项目结构通常包括 pom.xml 文件,其中明确了项目依赖和配置。以下是示例项目的 pom.xml 内容:

4.0.0
org.springframework.boot
spring-boot-starter-parent
2.4.2
com.example
demo
0.0.1-SNAPSHOT
demo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.session
spring-session-data-redis
org.springframework.boot
spring-boot-maven-plugin

应用程序配置

项目的 application.yml 配置文件通常用于定义应用程序的基本设置,包括会话管理和 Redis 配置。示例如下:

server:
port: 9002
servlet:
session:
timeout: 600 # 单位:秒。默认为30分钟,小于1分钟则自动设为1分钟。
# cookie相关配置,根据需要自行配置
spring:
session:
store-type: redis
redis:
database: 0 # Redis数据库索引(默认是0)
port: 6379
host: 192.168.5.193 # Redis服务器地址,建议根据实际情况配置
password: # Redis访问密码
# timeout: 0 # 单位:毫秒,默认为0,即阻塞直到连接成功或超时
lettuce:
pool:
max-active: 8 # 连接池最大连接数(默认为8)
max-idle: 8 # 连接池中最多空闲连接数,默认为8
max-wait: -1 # 最大阻塞等待时间(毫秒),默认为-1,无限制
min-idle: 0 # 最小空闲连接数,默认为0

启动类

应用程序的启动类通常位于 main 包下,示例代码如下:

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@SpringBootApplication
@EnableCaching
@EnableRedisHttpSession
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

实际开发

第一个示例

controller

package com.example.demo.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;
@RestController
@RequestMapping("simple")
public class SimpleController {
@GetMapping("get")
public Object get(HttpServletRequest request) {
return "sessionId:" + request.getSession().getId();
}
}

测试

同时以 9001/9002 端口启动 Spring Boot

访问 /simple/get 端点,可以看到带有当前会话 ID 的响应。

使用 Postman 测试
测试结果
  • 不带会话 cookie 访问:会生成新的 session ID,Redis 中会新增对应的 session 数据。
  • 带 cookie 访问:使用之前生成的 session ID,Redis 中不会新增会话数据,但会话 ID 保持不变。

自定义属性设置

controller

package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("custom")
public class CustomController {
@PostMapping("set")
public String set(HttpServletRequest request) {
request.getSession().setAttribute("myKey", "myValue");
return "success";
}
@GetMapping("get")
public Object get(HttpServletRequest request) {
return request.getSession().getAttribute("myKey");
}
}

测试

设置属性

访问 /custom/set 端点,Redis 中会新增对应的 key-value 对。

获取属性

访问 /custom/get 端点,可以从 Redis 中读取对应的 key-value 对。

登录和退出

controller

package com.example.demo.controller;
import com.example.demo.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
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.HashMap;
import java.util.Map;
@RestController
@RequestMapping("loginout")
public class LoginController {
Long id = 1L;
String name = "Tony";
String password = "123";
@PostMapping("login")
public String login(HttpServletRequest request, User user) {
if (!name.equals(user.getName()) || !password.equals(user.getPassword())) {
return "用户名或密码错误";
}
user.setId(id);
HttpSession session = request.getSession();
try {
ObjectMapper mapper = new ObjectMapper();
String userJson = mapper.writeValueAsString(user);
session.setAttribute(session.getId(), userJson);
return "登录成功";
} catch (Exception e) {
e.printStackTrace();
return "登录失败";
}
}
@PostMapping("logout")
public String logout(HttpServletRequest request) {
HttpSession session = request.getSession();
if (session != null) {
session.invalidate();
}
return "退出成功";
}
}

测试

登录
不带有效账户密码登录
登出

无论用户是否登录,调用 /loginout/logout 端点会销毁当前会话。

退出后再次登录
Redis存储

不同的操作会导致不同的 Redis 存储方式和频率,可以通过观察 Redis 集中存储情况来验证各类操作的行为。

高级功能

JSON 序列化优化

默认情况下,Spring 使用 JDK 序列化,但为了提高阅读性和性能,可以替换为 JSON 序列化。以下是优化后的配置类:

package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
@Configuration
public class RedisCacheConfig {
@Bean
public RedisSerializer springSessionDefaultRedisSerializer() {
return RedisSerializer.json();
}
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));
}
}

自定义键生成策略

可以通过自定义策略生成 Redis 的键,提升系统的可读性和管理性。


以上就是基于 Spring Boot 和 Redis 的一个完整会话管理实例,包含了从项目配置到实际开发测试的全流程。

转载地址:http://nstjz.baihongyu.com/

你可能感兴趣的文章
Objective-C实现KNN算法(附完整源码)
查看>>
Objective-C实现KNN算法(附完整源码)
查看>>
Objective-C实现knuth morris pratt(KMP)算法(附完整源码)
查看>>
Objective-C实现knuth-morris-pratt(KMP)算法(附完整源码)
查看>>
Objective-C实现Koch snowflake科赫雪花曲线算法(附完整源码)
查看>>
Objective-C实现koch snowflake科赫雪花算法(附完整源码)
查看>>
Objective-C实现KPCA(附完整源码)
查看>>
Objective-C实现KruskalMST最小生成树的算法(附完整源码)
查看>>
Objective-C实现kruskal克鲁斯卡尔算法(附完整源码)
查看>>
Objective-C实现kth order statistick阶统计量算法(附完整源码)
查看>>
Objective-C实现lamberts ellipsoidal distance朗伯椭球距离算法(附完整源码)
查看>>
Objective-C实现largest AdjacentNumber最大相邻数算法 (附完整源码)
查看>>
Objective-C实现largest subarray sum最大子数组和算法(附完整源码)
查看>>
Objective-C实现largestPrime最大素数的算法 (附完整源码)
查看>>
Objective-C实现lazy segment tree惰性段树算法(附完整源码)
查看>>
Objective-C实现LBP特征提取(附完整源码)
查看>>
Objective-C实现LDPC码(附完整源码)
查看>>
Objective-C实现least common multiple最小公倍数算法(附完整源码)
查看>>
Objective-C实现Lempel-Ziv压缩算法(附完整源码)
查看>>
Objective-C实现Length conversion长度转换算法(附完整源码)
查看>>