Microsoft提供了一个Redis供应程序,用来缓存Session,也就是说session信息都会缓存在Redis服务器中。这样我们可以实现分布式,提高网站的性能。
一、下载安装
在Visual Studio中,用Nutget下载Microsoft.Web.RedisSessionStateProvider包,
Install-Package Microsoft.Web.RedisSessionStateProvider
二、配置
cache-aspnet-session-state-provider官网
下载安装之后,会自动在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]
redisSerializerType = "<Assembly qualified class name that implements Microsoft.Web.Redis.ISerializer>" [String]
/>
-->
<add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" connectionString="localhost:6379,password=test123" applicationName="Test" host="" accessKey="" ssl="true" />
</providers>
</sessionState>
配置信息中,sessionState的timeout属性是我们自定义加上的,用来限制session过期期限,默认是30分钟,现在我们设置成15分钟。
我们设置applicationName=”Test”,由于redis服务会缓存多个程序的数据,所以我们需要用这个属性做区分,它会影响redis服务器生成key的名称。访问了会话之后我们可以看到自动生成的key-value:
当15分钟过去后,再去访问session值,redis管理器会提示找不到这个key.因为过了有效期,key-value会被回收。
对于配置信息,我这里有个疑问:
配置 host=”localhost” accessKey=”test123”,和connectionString=”localhost:6379,password=test123”,不是一样的吗,为啥前者连不上,后者才可以连上。。。。??