分布式Session如何存盤
一、介紹
Session(會話),用來記錄資訊確定用戶身份,保存在服務端,當客戶端瀏覽器訪問服務器時,服務器會把客戶端資訊保存在服務器上,這個就是Session,和Session對應的是Cookie,Cookie也是記錄資訊確定用戶身份的,不同的是,Cookie存盤在客戶端,Session存盤在服務端,一般會結合使用,Session存盤重要資訊,次要資訊使用Cookie存盤,
對比:
Session Cookie 存盤在服務端 存盤在客戶端 安全性高 安全性低,存盤在客戶端,可以獲取進行分析 訪問增多時,會占用服務器性能 保存在客戶端,會減輕服務器壓力 支持任意大小、型別的資料 資料不能超過4K,并且多數瀏覽器會顯示Cookie個數
二、分布式Session
在分布式系統中,我們需要考慮分布式事務、介面冪等性、分布式鎖、分布式Session等等,分布式事務我們可以使用阿里巴巴開源的seata框架解決,今天我們就來講講分布式Session,
三、實作方式
-
不使用Session
我們可以使用Token存盤用戶資訊,使用時從資料庫、快取中讀取,例如存盤在redis中,這樣請求無論到哪個服務器,我們都可以讀取到用戶資訊,也可以使用JWT,可以將用戶資訊加密到Token交給客戶端存盤,服務端不保存任何用戶資訊,只進行驗證,
-
使用Tomcat+Redis
我們可以在Tomcat的組態檔中進行設定,設定成功之后,Tomcat會將Session存盤到Redis中,這樣我們訪問不通的Tomcat時,可以保證session是共享的,
context.xml檔案
<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" host="127.0.0.1" port="6379" database="0" maxInactiveInterval="60"/> -
使用Spring Session+Redis
我們可以使用Spring Session和Redis實作共享存盤Session,這樣就不依賴部署的Web容器,下面我們簡單講解一些配置和使用,感興趣的小伙伴可以動手試試,
依賴:pom.xml
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.2.1.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency>組態檔:
<bean /> <bean > <property name="hostName" value="https://www.cnblogs.com/aibianchengya/archive/2022/10/23/127.0.0.1" /> <property name="password" value="https://www.cnblogs.com/aibianchengya/archive/2022/10/23/123654" /> <property name="port" value="https://www.cnblogs.com/aibianchengya/archive/2022/10/23/6379" /> <property name="database" value="https://www.cnblogs.com/aibianchengya/archive/2022/10/23/0" /> </bean>web.xml
<filter> <filter-name>springSessionRepositoryFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSessionRepositoryFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
原文鏈接:https://monkey.blog.xpyvip.top/archives/fen-bu-shi-session-ru-he-cun-chu
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519038.html
標籤:其他
上一篇:day51-正則運算式02
