2015年1月21日 星期三

Redis SessionStateProvider

首先開一個Web專案

安裝Microsoft.Web.RedisSessionStateProvider套件

設定檔中的sessionState自動會加入一段設定,註解的說明也很清楚
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <sessionState mode="Custom" customProvider="MySessionStateStore">
      <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]
          />
        -->
        <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="10.9.11.64" accessKey="" ssl="false" />
      </providers>
    </sessionState>
  </system.web>
</configuration>


隨便存取一個session
namespace WebApplication1
{
    using System;

    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var obj = Session["abc"];
            if (obj == null)
            {
                obj = DateTime.Now;
                Session["abc"] = obj;
            }

            Response.Write(Session.SessionID + "<br/>");
            Response.Write(obj);
        }
    }
}

網頁輸出的資料

Redis上面存放的資料