如果大家對spring boot不是很了解,大家可以參考下面兩篇文章。
這次帶來的是spring boot + redis 實(shí)現(xiàn)session共享的教程。
在spring boot的文檔中,告訴我們添加@EnableRedisHttpSession來開啟spring session支持,配置如下:
1
2
3
4
|
@Configuration @EnableRedisHttpSession public class RedisSessionConfig { } |
而@EnableRedisHttpSession這個注解是由spring-session-data-redis提供的,所以在pom.xml文件中添加:
1
2
3
4
5
6
7
8
|
<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服務(wù)器的位置了,在這里,我們就用本機(jī):
1
2
|
spring.redis.host=localhost spring.redis.port= 6379 |
這樣以來,最簡單的spring boot + redis實(shí)現(xiàn)session共享就完成了,下面進(jìn)行下測試。
首先我們開啟兩個tomcat服務(wù),端口分別為8080和9090,在application.properties中進(jìn)行設(shè)置【下載地址】 :
server.port=8080
接下來定義一個Controller:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@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; } } |
啟動之后進(jìn)行訪問測試,首先訪問8080端口的tomcat,返回 獲取【下載地址】 :
1
|
{ "request Url" : "http://localhost:8080/admin/v1/first" } |
接著,我們訪問8080端口的sessions,返回:
1
|
{ "sessionId" : "efcc85c0-9ad2-49a6-a38f-9004403776b5" , "message" :<a rel= "external nofollow" href= "http://localhost:8080/admin/v1/first" >http://localhost: 8080 /admin/v1/first</a>} |
最后,再訪問9090端口的sessions,返回:
1
|
{ "sessionId" : "efcc85c0-9ad2-49a6-a38f-9004403776b5" , "message" :<a rel= "external nofollow" href= "http://localhost:8080/admin/v1/first" >http://localhost: 8080 /admin/v1/first</a>} |
可見,8080與9090兩個服務(wù)器返回結(jié)果一樣,實(shí)現(xiàn)了session的共享
如果此時再訪問9090端口的first的話,首先返回:
1
|
{ "request Url" : "http://localhost:9090/admin/v1/first" } |
而兩個服務(wù)器的sessions都是返回:
1
|
{ "sessionId" : "efcc85c0-9ad2-49a6-a38f-9004403776b5" , "message" : "http://localhost:9090/admin/v1/first" } |
通過spring boot + redis來實(shí)現(xiàn)session的共享非常簡單,而且用處也極大,配合nginx進(jìn)行負(fù)載均衡,便能實(shí)現(xiàn)分布式的應(yīng)用了。
本次的redis并沒有進(jìn)行主從、讀寫分離等等配置(_(:з」∠)_其實(shí)是博主懶,還沒嘗試過.......)
而且,nginx的單點(diǎn)故障也是我們應(yīng)用的障礙......以后可能會有對此次博客的改進(jìn)版本,比如使用zookeeper進(jìn)行負(fù)載均衡,敬請期待。
好了,到此結(jié)束吧,以上所述是小編給大家介紹的spring boot與redis 實(shí)現(xiàn)session共享教程,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/mengmeng89012/p/5519698.html