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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Session使用

發布時間:2025/3/15 javascript 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Session使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、session的處理方式

參考本人這篇文章

二、spring session使用的session管理方式

就是Session集中管理的方式:

  • 優點:可靠性高,減少Web服務器的資源開銷。
  • 缺點:實現上有些復雜,配置較多。
  • 適用場景:Web服務器較多、要求高可用性的情況。

三、spring session的實現思路

  • HttpSession的管理

HttpSession是通過Servlet容器創建和管理的,像Tomcat/Jetty都是保存在內存中的。但是把應用搭建成分布式的集群,然后利用F5、LVS或Nginx做負載均衡,那么來自同一用戶的Http請求將有可能被分發到多個不同的服務器中。那問題來了,如何保證不同的服務器能夠共享同一份session數據呢?最簡單的想法,就是把session數據保存到內存以外的一個統一的地方,例如Memcached/Redis等數據庫中。那問題又來了,如何替換掉Servlet容器創建和管理的HttpSession的實現呢?

  • 方案一:利用Servlet容器提供的插件功能,自定義HttpSession的創建和管理策略,并通過配置的方式替換掉默認的策略。這方面其實早就有開源項目了,例如memcached-session-manager(可以參考負載均衡+session共享(memcached-session-manager實現),以及tomcat-redis-session-manager。不過這種方式有個缺點,就是需要耦合Tomcat/Jetty等Servlet容器的代碼。
  • 方案二:設計一個Filter,利用HttpServletRequestWrapper,實現自己的getSession()方法,接管創建和管理Session數據的工作。spring-session就是通過這樣的思路實現的。

四、代碼例子

  • pom.xml
  • <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId></dependency></dependencies>
  • config類
  • @Configuration public class RedisConfig {// 將spring session中的序列化器替換成json的,默認的jdk序列化機制太費勁了@Beanpublic GenericJackson2JsonRedisSerializer springSessionDefaultRedisSerializer() {return new GenericJackson2JsonRedisSerializer();} }
  • entity
  • @Data @AllArgsConstructor @NoArgsConstructor public class User implements Serializable {Long id;Integer age;String position;String userName; }
  • controller
  • @RestController public class UserController {private static final Logger logger = LoggerFactory.getLogger(UserController.class);/*** 把用戶放入session* @param request* @return*/@RequestMapping("/user/login")@ResponseBodypublic Map<String, Object> login(HttpServletRequest request) {// 取出session中的userNameObject loginUser = request.getSession().getAttribute("loginUser");if (loginUser == null) {logger.info("不存在session,設置user");User u = new User();u.setAge(23);u.setId(1L);u.setPosition("總裁");u.setUserName("cristiano ronaldo");request.getSession().setAttribute("loginUser", u);} else {logger.info("存在session,user=" + JSON.toJSONString(loginUser));}Cookie[] cookies = request.getCookies();if (cookies != null && cookies.length > 0) {for (Cookie cookie : cookies) {logger.info(cookie.getName() + " : " + cookie.getValue());}}Map<String, Object> resp = new HashMap<String, Object>();resp.put("code", "000000");resp.put("msg", "交易成功");return resp;}/*** 獲取session的用戶* @param request* @return*/@RequestMapping("/user/getUser")@ResponseBodypublic Map<String, Object> getUser(HttpServletRequest request) {Map<String, Object> resp = new HashMap<>();resp.put("code", "000000");resp.put("msg", "交易成功");resp.put("body", request.getSession().getAttribute("loginUser"));Cookie[] cookies = request.getCookies();if (cookies != null && cookies.length > 0) {for (Cookie cookie : cookies) {logger.info(cookie.getName() + " : " + cookie.getValue());}}return resp;} }
  • application.yml
  • server:port: 8888 spring:session:store-type: redisapplication:name: s-sessionredis:host: xxpassword: xxport: 6379timeout: 10000 # 連接超時時間(毫秒)database: 3 # Redis默認情況下有16個分片,這里配置具體使用的分片,默認是0lettuce:pool:max-active: 8 # 連接池最大連接數(使用負值表示沒有限制) 默認 8max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1max-idle: 8 # 連接池中的最大空閑連接 默認 8min-idle: 0 # 連接池中的最小空閑連接 默認 0
  • 首次訪問 http://127.0.0.1:8888/user/login

    再次訪問 http://127.0.0.1:8888/user/login

  • 可以看到,redis中已經是以json的形式保存session了

    與50位技術專家面對面20年技術見證,附贈技術全景圖

    總結

    以上是生活随笔為你收集整理的Spring Session使用的全部內容,希望文章能夠幫你解決所遇到的問題。

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