日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot+redis实现分布式session共享

發布時間:2024/9/5 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot+redis实现分布式session共享 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

官方文檔,它是spring session項目的redis相關的一個子文檔:https://docs.spring.io/spring-session/docs/2.0.0.BUILD-SNAPSHOT/reference/html5/guides/boot-redis.html

?

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

@Configuration @EnableRedisHttpSession public class RedisSessionConfig { }

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

<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里配置spring session

spring.session.store-type=redis #指定redis實現spring session server.session.timeout=600 # Session 過期時間,單位s spring.session.redis.flush-mode= # Sessions 刷新模式 spring.session.redis.namespace= # Namespace for keys used to store sessions.

配置redis連接信息

spring.redis.host=localhost spring.redis.password=secret spring.redis.port=6379

加上端口號

server.port=8080

定義一個Controller

@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; } }

復制上面的工程,把port改為9090

兩個項目都啟動好

首先訪問8080端口的設置session

{"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,返回:

{"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"}

這個時候打開redis客戶端,可以查詢到session信息已經保存在redis里。

注意點:

1.Redis版本要在2.8+

轉載于:https://www.cnblogs.com/heyy520/p/9899279.html

總結

以上是生活随笔為你收集整理的springboot+redis实现分布式session共享的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。