您的位置:首页 > 数据库 > Redis

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

2017-03-11 15:23 561 查看
近日一直在尝试建立一个真正高可用的负载平衡的方式,可以大大缩减因程序版本更新/服务器维护/突发异常等等导致的服务停止时间.要让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上的数据

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  session redis asp.net