1. 程式人生 > >Redis學習筆記~StackExchange.Redis實現分散式Session

Redis學習筆記~StackExchange.Redis實現分散式Session

回到目錄

對於多WEB的環境現在已經是必須的了,很難想像一臺WEB伺服器面對百萬併發的響應,所以,我們需要多臺WEB伺服器叢集合作,來緩解這種高併發,高吞吐的場景,而對於多WEB的場景又會有個問題出現,即session儲存的問題,如一個使用者登陸後,把一個狀態資訊儲存到當前WEB伺服器的session裡,而你請求其它頁面時,很可能就被路由到另一臺伺服器了,這時,session也就丟了,而對於這種情況,有人把redis這個儲存中介軟體想了起來,對它進行了封裝,就有了今天基於redis的session共享機制。

下面說下安裝方法

1 使用nuget安裝redis快取 StackExchange.Redis
2 使用nuget安裝RedisSession服務  RedisSessionStateProvider
3 從nuget新增RedisSession之後,它會在你的config檔案中寫入以下內容,主要是對session進行持久化設定的
   

<sessionState mode="Custom" customProvider="MySessionStateStore" timeout="30">
      <providers>
        <!-- Either use 'connectionString' and provide all parameters as string OR use 'host','port','accessKey','ssl','connectionTimeoutInMilliseconds' and 'operationTimeoutInMilliseconds
'. --> <!-- 'throwOnError','retryTimeoutInMilliseconds','databaseId' and 'applicationName' can be used with both options. --> <!-- <add name="MySessionStateStore" host = "127.0.0.1" [String] port = "" [number] accessKey
= "" [String] ssl = "false" [true|false] throwOnError = "true" [true|false] retryTimeoutInMilliseconds = "5000" [number] databaseId = "0" [number] applicationName = "" [String] connectionTimeoutInMilliseconds = "5000" [number] operationTimeoutInMilliseconds = "1000" [number] connectionString = "<Valid StackExchange.Redis connection string>" [String] loggingClassName = "<Assembly qualified class name that contains logging method specified below>" [String] loggingMethodName = "<Logging method should be defined in loggingClass. It should be public, static, does not take any parameters and should have a return type of System.IO.TextWriter.>" [String] /> --> <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" /> </providers> </sessionState>


4 下載是新版本的redis服務端,可以是windows版的,我用的是2.6.13,低版本的redis會出現Eval命令無法識別的問題
5 處理完成,可以測試你的session了,預設過期時間為1200秒

注意,上面sessionState裡的timeout就是設定session超時的,它同樣使用於redis的儲存,下面是存在redis裡的session,如圖

感謝我VIP群的哥們提出這個問題,並對session超時的設定進行了解決。

回到目錄