spring boot + redis 實現session共享

這次帶來的是spring boot + redis 實現session共享的教程。

 

在spring boot的文檔中,告訴我們添加@EnableRedisHttpSession來開啓spring session支持,配置如下:

Java代碼  收藏代碼

  1. @Configuration  

  2. @EnableRedisHttpSession  

  3. public class RedisSessionConfig {  

  4. }  

而@EnableRedisHttpSession這個註解是由spring-session-data-redis提供的,所以在pom.xml文件中添加:

Java代碼  收藏代碼

  1. <dependency>  

  2.         <groupId>org.springframework.boot</groupId>  

  3.         <artifactId>spring-boot-starter-redis</artifactId>  

  4. </dependency>  

  5. <dependency>  

  6.         <groupId>org.springframework.session</groupId>  

  7.         <artifactId>spring-session-data-redis</artifactId>  

  8. </dependency>  

 

 

接下來,則需要在application.properties中配置redis服務器的位置了,在這裏,我們就用本機:

Java代碼  收藏代碼

  1. spring.redis.host=localhost  

  2. spring.redis.port=6379  

這樣以來,最簡單的spring boot + redis實現session共享就完成了,下面進行下測試。

 

首先我們開啓兩個tomcat服務,端口分別爲8080和9090,在application.properties中進行設置【下載地址】   

Java代碼  收藏代碼

  1. server.port=8080  

 

接下來定義一個Controller: 

Java代碼  收藏代碼

  1. @RestController  

  2. @RequestMapping(value = "/admin/v1")  

  3. public class QuickRun {  

  4.     @RequestMapping(value = "/first", method = RequestMethod.GET)  

  5.     public Map<String, Object> firstResp (HttpServletRequest request){  

  6.         Map<String, Object> map = new HashMap<>();  

  7.         request.getSession().setAttribute("request Url", request.getRequestURL());  

  8.         map.put("request Url", request.getRequestURL());  

  9.         return map;  

  10.     }  

  11.   

  12.     @RequestMapping(value = "/sessions", method = RequestMethod.GET)  

  13.     public Object sessions (HttpServletRequest request){  

  14.         Map<String, Object> map = new HashMap<>();  

  15.         map.put("sessionId", request.getSession().getId());  

  16.         map.put("message", request.getSession().getAttribute("map"));  

  17.         return map;  

  18.     }  

  19. }  

 

啓動之後進行訪問測試,首先訪問8080端口的tomcat,返回 獲取【下載地址】   

Java代碼  收藏代碼

  1. {"request Url":"http://localhost:8080/admin/v1/first"}  

 接着,我們訪問8080端口的sessions,返回:

Java代碼  收藏代碼

  1. {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}  

最後,再訪問9090端口的sessions,返回:

Java代碼  收藏代碼

  1. {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}  

可見,8080與9090兩個服務器返回結果一樣,實現了session的共享

 

如果此時再訪問9090端口的first的話,首先返回:

Java代碼  收藏代碼

  1. {"request Url":"http://localhost:9090/admin/v1/first"}  

而兩個服務器的sessions都是返回:

Java代碼  收藏代碼

  1. {"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:9090/admin/v1/first"}  

 

通過spring boot + redis來實現session的共享非常簡單,而且用處也極大,配合nginx進行負載均衡,便能實現分佈式的應用了。

本次的redis並沒有進行主從、讀寫分離等等配置(_(:з」∠)_其實是博主懶,還沒嘗試過.......)

而且,nginx的單點故障也是我們應用的障礙......以後可能會有對此次博客的改進版本,比如使用zookeeper進行負載均衡,敬請期待。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章