详解Asp.net Core 使用Redis存储Session(3)

using System.Threading.Tasks; using StackExchange.Redis; namespace Microsoft.Extensions.Caching.Redis { internal static class RedisExtensions { private const string HmGetScript = (@"return redis.call('HMGET', KEYS[1], unpack(ARGV))"); internal static RedisValue[] HashMemberGet(this IDatabase cache, string key, params string[] members) { var result = cache.ScriptEvaluate( HmGetScript, new RedisKey[] { key }, GetRedisMembers(members)); // TODO: Error checking? return (RedisValue[])result; } internal static async Task<RedisValue[]> HashMemberGetAsync( this IDatabase cache, string key, params string[] members) { var result = await cache.ScriptEvaluateAsync( HmGetScript, new RedisKey[] { key }, GetRedisMembers(members)); // TODO: Error checking? return (RedisValue[])result; } private static RedisValue[] GetRedisMembers(params string[] members) { var redisMembers = new RedisValue[members.Length]; for (int i = 0; i < members.Length; i++) { redisMembers[i] = (RedisValue)members[i]; } return redisMembers; } } }

配置启用Session

我们在Startup中ConfigureServices增加

services.AddSingleton<IDistributedCache>( serviceProvider => new RedisCache(new RedisCacheOptions { Configuration = "192.168.178.141:6379", InstanceName = "Sample:" })); services.AddSession();

在Startup中Configure增加

app.UseSession(new SessionOptions() { IdleTimeout = TimeSpan.FromMinutes(30) });

到此我们的配置完毕,可以测试一下是否写到了Redis中

验证结果

在Mvc项目中,我们来实现如下代码

if (string.IsNullOrEmpty(HttpContext.Session.GetString("D"))) { var d = DateTime.Now.ToString(); HttpContext.Session.SetString("D", d); HttpContext.Response.ContentType = "text/plain"; await HttpContext.Response.WriteAsync("Hello First timer///" + d); } else { HttpContext.Response.ContentType = "text/plain"; await HttpContext.Response.WriteAsync("Hello old timer///" + HttpContext.Session.GetString("D")); }

运行我们发现第一次出现了Hello First timer字样,刷新后出现了Hello old timer字样,证明Session成功,再查看一下Redis看一下,有值了,这样一个分布式的Session就成功实现了。

对于上面的实例我把源码放在了:demo下载

Tianwei.Microsoft.Extensions.Caching.Redis ,只是ID加了Tianwei 空间名还是Microsoft.Extensions.Caching.Redis

从上面的实例我们发现微软这次是真的开放了,这也意味着如果我们使用某些类不顺手或不合适时可以自已写自已扩展

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjywsf.html