asp.net使用redis存儲session(RedisSessionStateProvider)

近日一直在嘗試建立一個真正高可用的負載平衡的方式,可以大大縮減因程序版本更新/服務器維護/突發異常等等導致的服務停止時間.要讓web站點實現真正的高可用,勢必要進行session共享,防止某一服務器down掉時session也跟着丟失.
通過不斷的Google,最終我選擇使用微軟提供的RedisSessionStateProvider進行session的託管.
使用這個方式的優點:
1.無需自己擴展session provider,對自己代碼能力不夠自信的小夥伴們放心選擇~
2.無需修改現有代碼,只需透過web.config配置即可.

這個方式使用起來非常簡單,通過nuget安裝RedisSessionStateProvider組件,然後修改web.config即可.

1.通過nuget安裝RedisSessionStateProvider

這裏寫圖片描述

2.修改web.config配置的Host與port節點,並將ssl改成false.

<sessionState mode="Custom" customProvider="MySessionStateStore">
      <providers>
        <!-- For more details check https://github.com/Azure/aspnet-redis-providers/wiki -->
        <!-- Either use 'connectionString' OR 'settingsClassName' and 'settingsMethodName' 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]
            settingsClassName = "<Assembly qualified class name that contains settings method specified below. Which basically return 'connectionString' value>" [String]
            settingsMethodName = "<Settings method should be defined in settingsClass. It should be public, static, does not take any parameters and should have a return type of 'String', which is basically 'connectionString' value.>" [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]
            redisSerializerType = "<Assembly qualified class name that implements Microsoft.Web.Redis.ISerializer>" [String]
          />
        -->
        <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="192.168.0.97"  port="6379" accessKey="" ssl="false" />
      </providers>
    </sessionState>

3.測試
頁面上取得的sessionid與redis存儲的一致,證明我們的session數據已經可以順利存到redis啦.

頁面上取到的session Id
這裏寫圖片描述

redis上的數據
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章