多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# springboot redis 分布式session ## 1.有状态服务和无状态服务 ![](https://box.kancloud.cn/d87a6f0cb396c3d23c80fde4c9a7669b_641x457.png) ### 1.1 无状态服务 经过负载,在web1和web2session一致. ### 1.2 有状态服务 经过负载,在web1和web2session不一致. ## 2. 实现无状态服务(session统一管理) 实现有状态到无状态的有两种: 1. session统一管理 2. 负载策略 ### 2.1 springboot + redis 实现分布式session #### 2.1.1 pom引入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.1.2 配置redis session ``` @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 30 * 60 * 1000) public class RedisSessionConfig { @Bean public static ConfigureRedisAction configureRedisAction() { return ConfigureRedisAction.NO_OP; } } ``` #### 2.1.3 加入redis连接配置 ``` redis: database: 0 host: 192.168.56.10 password: 密码 port: 6379 ``` #### 2.1.4 controller ``` @GetMapping(value = "/session_test") @ResponseBody public String test4(HttpSession session){ UUID uid = (UUID) session.getAttribute("uid"); if (uid == null) { uid = UUID.randomUUID(); } session.setAttribute("uid", uid); return session.getId(); } ``` #### 2.1.5 测试 启动两个应用(端口8888,端口8889) ![](https://box.kancloud.cn/85e07ebe31d83953ab03d87ee40702ee_586x196.png) ![](https://box.kancloud.cn/0bfbb29f6a8f4ff069bac68b652b7cf9_562x209.png) 实现了统一域名下的session共享