ASP.NET MVC Redis实现Session

 

1:Nuget安装StackExchange.Redis

2:Nuget安装RedisSessionStateProvider

在web.config

<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]
          />
        -->
        <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" 
             connectionString="127.0.0.1:6379,password=123456,ssl=false,abortConnect=false,connectTimeout=5000" host="" accessKey="" ssl="true" />
      </providers>
    </sessionState>

在代码中使用session

 Session["maimai"] = "麦麦";

 Session["haha"] = "哈哈";

redis会生成两个Hash key,如下

{/_jih5op0z3n0pcoo3amv32p3n}_Data

{/_jih5op0z3n0pcoo3amv32p3n}_Internal

Data保存所有的session数据,Internal保存session的过期时间,截图如下

 

jih5op0z3n0pcoo3amv32p3n 这一串就是我们的sessionId,如下图

 

再添加一个session测试一下,

 Session["haha"] = "哈哈";

 https://docs.microsoft.com/zh-cn/azure/redis-cache/cache-aspnet-session-state-provider

posted @ 2017-08-24 22:17  败草麦麦  阅读(361)  评论(0编辑  收藏  举报