此次帶來的是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進行負載均衡,敬請期待。