模拟多节点服务器环境,通过一套代码不同端口实现,最终判断获取的sessionID一致即实现共享;
【java -jar --server -port=8000,通过启动命令配置各种信息的优先级最高】
1.创建springboot-redis-session项目,配置pom.xml依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.0.4.RELEASE</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
2.配置application.properties文件建立redis连接池
#server.port=8010 //此处注释掉,在启动访问时通过java -jar --server -port=8000添加 ######################################################## ###REDIS (RedisProperties) redis基本配置; ######################################################## # database name spring.redis.database=0 # server host1 单机使用,对应服务器ip spring.redis.host=192.168.1.11 # server password 密码,如果没有设置可不配 #spring.redis.password= #connection port 单机使用,对应端口号 spring.redis.port=10179 # pool settings ...池配置 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1
3.创建config/RedisSessionConfig
package com.cc.springbootredissession.config; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration @EnableRedisHttpSession //引入此注解代表此类开启HttpSession共享功能 public class RedisSessionConfig { }
4.创建controller/SessionController
ackage com.cc.springbootredissession.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 java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/sessions") public class SessionController { //设置session @GetMapping("set") public Map<String,Object> setSession(HttpServletRequest request){ Map<String,Object> map = new HashMap<>(); request.getSession().setAttribute("uri",request.getRequestURL()); map.put("uri",request.getRequestURL()); return map; } //获取session @GetMapping("list") public Map<String,Object> getSession(HttpServletRequest request){ Map<String ,Object> map = new HashMap<>(); map.put("sessionID",request.getSession().getId()); map.put("uri",request.getSession().getAttribute("uri")); return map; } }
5.使用maven封装程序jar包执行:
(进入程序所在目录)
D:\IDEA\springboot-redis-session\mvn package
封装完成后,进入target运行程序
D:\IDEA\springboot-redis-session\target>java -jar spring-redis-session-0.0.1-SNAPSHOT.jar --server.post=9100
为模拟多节点,在新开终端启动一个程序,更端口为9101;
6.启动完成后通过浏览器访问:
最终结果显示,sessionID一致,模拟完成!