源码地址:https://github.com/JianLiangHe/springboot-conformity/tree/master/springboot-conformity-session01
1.Maven依赖
SpringBoot和Spring Session整合的配置需要引入2个依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
2.application.yml
server: port: 8088 spring: # redis配置 redis: # ip地址 host: 139.196.158.120 # 端口 port: 26379 # 密码 password: root
3.RedisSessionConfig.java 配置类
@Configuration // maxInactiveIntervalInSeconds 默认是1800秒过期,这里改为60秒 // RedisFlushMode有两个参数:ON_SAVE(表示在response commit前刷新缓存),IMMEDIATE(表示只要有更新,就刷新缓存) // redisNamespace : redis中的key @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60, redisFlushMode = RedisFlushMode.ON_SAVE, redisNamespace = "springboot-conformity-session01") public class RedisSessionConfig { }
4.添加测试Controller:SessionShareController.java
@Api @RestController @RequestMapping(value = "/sessionShare/") public class SessionShareController { @Value("${server.port}") private Integer port; @ApiOperation("set") @RequestMapping(value = "set", method = RequestMethod.POST) public String set(HttpSession session) { session.setAttribute("user", "Jackey"); return String.valueOf(port); } @ApiOperation("get") @RequestMapping(value = "get", method = RequestMethod.GET) public String get(HttpSession session) { return "user: " + session.getAttribute("user") + ", port: " + port; } }
5.测试结果
1.将项目打成jar包,发布到服务器,过程略,分别使用9090、9091端口启动项目
nohup java -jar springboot-conformity-session01-0.0.1-SNAPSHOT.jar --server.port=9090 &
nohup java -jar springboot-conformity-session01-0.0.1-SNAPSHOT.jar --server.prot=9091 &
先访问9090端口的服务set方法(此处我用swagger接口文档访问)
再用9090和9091端口访问get方法
9090:
9091:
从上面案例看,可以看出session已经实现了共享。