此次带来的是spring boot + redis 实现session共享的教程。nginx
在spring boot的文档中,告诉咱们添加@EnableRedisHttpSession来开启spring session支持,配置以下:redis
- @Configuration
- @EnableRedisHttpSession
- public class RedisSessionConfig {
- }
而@EnableRedisHttpSession这个注解是由spring-session-data-redis提供的,因此在pom.xml文件中添加:spring
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-redis</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.session</groupId>
- <artifactId>spring-session-data-redis</artifactId>
- </dependency>
接下来,则须要在application.properties中配置redis服务器的位置了,在这里,咱们就用本机:tomcat
- spring.redis.host=localhost
- spring.redis.port=6379
这样以来,最简单的spring boot + redis实现session共享就完成了,下面进行下测试。服务器
首先咱们开启两个tomcat服务,端口分别为8080和9090,在application.properties中进行设置【下载地址】 :session
接下来定义一个Controller: app
- @RestController
- @RequestMapping(value = "/admin/v1")
- public class QuickRun {
- @RequestMapping(value = "/first", method = RequestMethod.GET)
- public Map<String, Object> firstResp (HttpServletRequest request){
- Map<String, Object> map = new HashMap<>();
- request.getSession().setAttribute("request Url", request.getRequestURL());
- map.put("request Url", request.getRequestURL());
- return map;
- }
-
- @RequestMapping(value = "/sessions", method = RequestMethod.GET)
- public Object sessions (HttpServletRequest request){
- Map<String, Object> map = new HashMap<>();
- map.put("sessionId", request.getSession().getId());
- map.put("message", request.getSession().getAttribute("map"));
- return map;
- }
- }
启动以后进行访问测试,首先访问8080端口的tomcat,返回 获取【下载地址】 :负载均衡
- {"request Url":"http://localhost:8080/admin/v1/first"}
接着,咱们访问8080端口的sessions,返回:分布式
- {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}
最后,再访问9090端口的sessions,返回:spring-boot
- {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}
可见,8080与9090两个服务器返回结果同样,实现了session的共享
若是此时再访问9090端口的first的话,首先返回:
- {"request Url":"http://localhost:9090/admin/v1/first"}
而两个服务器的sessions都是返回:
- {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:9090/admin/v1/first"}
经过spring boot + redis来实现session的共享很是简单,并且用处也极大,配合nginx进行负载均衡,便能实现分布式的应用了。
本次的redis并无进行主从、读写分离等等配置(_(:з」∠)_实际上是博主懒,还没尝试过.......)
并且,nginx的单点故障也是咱们应用的障碍......之后可能会有对这次博客的改进版本,好比使用zookeeper进行负载均衡,敬请期待。