当前位置:Gxlcms > asp.net > 详解Asp.net Core 使用Redis存储Session

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

时间:2021-07-01 10:21:17 帮助过:34人阅读

前言

Asp.net Core 改变了之前的封闭,现在开源且开放,下面我们来用Redis存储Session来做一个简单的测试,或者叫做中间件(middleware)。

对于Session来说褒贬不一,很多人直接说不要用,也有很多人在用,这个也没有绝对的这义,个人认为只要不影什么且又可以方便实现的东西是可以用的,现在不对可不可用做表态,我们只关心实现。

类库引用

这个相对于之前的.net是方便了不少,需要在project.json中的dependencies节点中添加如下内容:

  1. "StackExchange.Redis": "1.1.604-alpha",
  2. "Microsoft.AspNetCore.Session": "1.1.0-alpha1-21694"

Redis实现

这里并非我实现,而是借用不知道为什么之前还有这个类库,而现在NUGET止没有了,为了不影响日后升级我的命名空间也用 Microsoft.Extensions.Caching.Redis

可以看到微软这里有四个类,其实我们只需要三个,第四个拿过来反而会出错:

  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.Extensions.Caching.Distributed;
  4. using Microsoft.Extensions.Options;
  5. using StackExchange.Redis;
  6. namespace Microsoft.Extensions.Caching.Redis
  7. {
  8. public class RedisCache : IDistributedCache, IDisposable
  9. {
  10. // KEYS[1] = = key
  11. // ARGV[1] = absolute-expiration - ticks as long (-1 for none)
  12. // ARGV[2] = sliding-expiration - ticks as long (-1 for none)
  13. // ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration)
  14. // ARGV[4] = data - byte[]
  15. // this order should not change LUA script depends on it
  16. private const string SetScript = (@"
  17. redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
  18. if ARGV[3] ~= '-1' then
  19. redis.call('EXPIRE', KEYS[1], ARGV[3])
  20. end
  21. return 1");
  22. private const string AbsoluteExpirationKey = "absexp";
  23. private const string SlidingExpirationKey = "sldexp";
  24. private const string DataKey = "data";
  25. private const long NotPresent = -1;
  26. private ConnectionMultiplexer _connection;
  27. private IDatabase _cache;
  28. private readonly RedisCacheOptions _options;
  29. private readonly string _instance;
  30. public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
  31. {
  32. if (optionsAccessor == null)
  33. {
  34. throw new ArgumentNullException(nameof(optionsAccessor));
  35. }
  36. _options = optionsAccessor.Value;
  37. // This allows partitioning a single backend cache for use with multiple apps/services.
  38. _instance = _options.InstanceName ?? string.Empty;
  39. }
  40. public byte[] Get(string key)
  41. {
  42. if (key == null)
  43. {
  44. throw new ArgumentNullException(nameof(key));
  45. }
  46. return GetAndRefresh(key, getData: true);
  47. }
  48. public async Task<byte[]> GetAsync(string key)
  49. {
  50. if (key == null)
  51. {
  52. throw new ArgumentNullException(nameof(key));
  53. }
  54. return await GetAndRefreshAsync(key, getData: true);
  55. }
  56. public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
  57. {
  58. if (key == null)
  59. {
  60. throw new ArgumentNullException(nameof(key));
  61. }
  62. if (value == null)
  63. {
  64. throw new ArgumentNullException(nameof(value));
  65. }
  66. if (options == null)
  67. {
  68. throw new ArgumentNullException(nameof(options));
  69. }
  70. Connect();
  71. var creationTime = DateTimeOffset.UtcNow;
  72. var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);
  73. var result = _cache.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key },
  74. new RedisValue[]
  75. {
  76. absoluteExpiration?.Ticks ?? NotPresent,
  77. options.SlidingExpiration?.Ticks ?? NotPresent,
  78. GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent,
  79. value
  80. });
  81. }
  82. public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
  83. {
  84. if (key == null)
  85. {
  86. throw new ArgumentNullException(nameof(key));
  87. }
  88. if (value == null)
  89. {
  90. throw new ArgumentNullException(nameof(value));
  91. }
  92. if (options == null)
  93. {
  94. throw new ArgumentNullException(nameof(options));
  95. }
  96. await ConnectAsync();
  97. var creationTime = DateTimeOffset.UtcNow;
  98. var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);
  99. await _cache.ScriptEvaluateAsync(SetScript, new RedisKey[] { _instance + key },
  100. new RedisValue[]
  101. {
  102. absoluteExpiration?.Ticks ?? NotPresent,
  103. options.SlidingExpiration?.Ticks ?? NotPresent,
  104. GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent,
  105. value
  106. });
  107. }
  108. public void Refresh(string key)
  109. {
  110. if (key == null)
  111. {
  112. throw new ArgumentNullException(nameof(key));
  113. }
  114. GetAndRefresh(key, getData: false);
  115. }
  116. public async Task RefreshAsync(string key)
  117. {
  118. if (key == null)
  119. {
  120. throw new ArgumentNullException(nameof(key));
  121. }
  122. await GetAndRefreshAsync(key, getData: false);
  123. }
  124. private void Connect()
  125. {
  126. if (_connection == null)
  127. {
  128. _connection = ConnectionMultiplexer.Connect(_options.Configuration);
  129. _cache = _connection.GetDatabase();
  130. }
  131. }
  132. private async Task ConnectAsync()
  133. {
  134. if (_connection == null)
  135. {
  136. _connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration);
  137. _cache = _connection.GetDatabase();
  138. }
  139. }
  140. private byte[] GetAndRefresh(string key, bool getData)
  141. {
  142. if (key == null)
  143. {
  144. throw new ArgumentNullException(nameof(key));
  145. }
  146. Connect();
  147. // This also resets the LRU status as desired.
  148. // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
  149. RedisValue[] results;
  150. if (getData)
  151. {
  152. results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
  153. }
  154. else
  155. {
  156. results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey);
  157. }
  158. // TODO: Error handling
  159. if (results.Length >= 2)
  160. {
  161. // Note we always get back two results, even if they are all null.
  162. // These operations will no-op in the null scenario.
  163. DateTimeOffset? absExpr;
  164. TimeSpan? sldExpr;
  165. MapMetadata(results, out absExpr, out sldExpr);
  166. Refresh(key, absExpr, sldExpr);
  167. }
  168. if (results.Length >= 3 && results[2].HasValue)
  169. {
  170. return results[2];
  171. }
  172. return null;
  173. }
  174. private async Task<byte[]> GetAndRefreshAsync(string key, bool getData)
  175. {
  176. if (key == null)
  177. {
  178. throw new ArgumentNullException(nameof(key));
  179. }
  180. await ConnectAsync();
  181. // This also resets the LRU status as desired.
  182. // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
  183. RedisValue[] results;
  184. if (getData)
  185. {
  186. results = await _cache.HashMemberGetAsync(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
  187. }
  188. else
  189. {
  190. results = await _cache.HashMemberGetAsync(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey);
  191. }
  192. // TODO: Error handling
  193. if (results.Length >= 2)
  194. {
  195. // Note we always get back two results, even if they are all null.
  196. // These operations will no-op in the null scenario.
  197. DateTimeOffset? absExpr;
  198. TimeSpan? sldExpr;
  199. MapMetadata(results, out absExpr, out sldExpr);
  200. await RefreshAsync(key, absExpr, sldExpr);
  201. }
  202. if (results.Length >= 3 && results[2].HasValue)
  203. {
  204. return results[2];
  205. }
  206. return null;
  207. }
  208. public void Remove(string key)
  209. {
  210. if (key == null)
  211. {
  212. throw new ArgumentNullException(nameof(key));
  213. }
  214. Connect();
  215. _cache.KeyDelete(_instance + key);
  216. // TODO: Error handling
  217. }
  218. public async Task RemoveAsync(string key)
  219. {
  220. if (key == null)
  221. {
  222. throw new ArgumentNullException(nameof(key));
  223. }
  224. await ConnectAsync();
  225. await _cache.KeyDeleteAsync(_instance + key);
  226. // TODO: Error handling
  227. }
  228. private void MapMetadata(RedisValue[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration)
  229. {
  230. absoluteExpiration = null;
  231. slidingExpiration = null;
  232. var absoluteExpirationTicks = (long?)results[0];
  233. if (absoluteExpirationTicks.HasValue && absoluteExpirationTicks.Value != NotPresent)
  234. {
  235. absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks.Value, TimeSpan.Zero);
  236. }
  237. var slidingExpirationTicks = (long?)results[1];
  238. if (slidingExpirationTicks.HasValue && slidingExpirationTicks.Value != NotPresent)
  239. {
  240. slidingExpiration = new TimeSpan(slidingExpirationTicks.Value);
  241. }
  242. }
  243. private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
  244. {
  245. if (key == null)
  246. {
  247. throw new ArgumentNullException(nameof(key));
  248. }
  249. // Note Refresh has no effect if there is just an absolute expiration (or neither).
  250. TimeSpan? expr = null;
  251. if (sldExpr.HasValue)
  252. {
  253. if (absExpr.HasValue)
  254. {
  255. var relExpr = absExpr.Value - DateTimeOffset.Now;
  256. expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
  257. }
  258. else
  259. {
  260. expr = sldExpr;
  261. }
  262. _cache.KeyExpire(_instance + key, expr);
  263. // TODO: Error handling
  264. }
  265. }
  266. private async Task RefreshAsync(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
  267. {
  268. if (key == null)
  269. {
  270. throw new ArgumentNullException(nameof(key));
  271. }
  272. // Note Refresh has no effect if there is just an absolute expiration (or neither).
  273. TimeSpan? expr = null;
  274. if (sldExpr.HasValue)
  275. {
  276. if (absExpr.HasValue)
  277. {
  278. var relExpr = absExpr.Value - DateTimeOffset.Now;
  279. expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
  280. }
  281. else
  282. {
  283. expr = sldExpr;
  284. }
  285. await _cache.KeyExpireAsync(_instance + key, expr);
  286. // TODO: Error handling
  287. }
  288. }
  289. private static long? GetExpirationInSeconds(DateTimeOffset creationTime, DateTimeOffset? absoluteExpiration, DistributedCacheEntryOptions options)
  290. {
  291. if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue)
  292. {
  293. return (long)Math.Min(
  294. (absoluteExpiration.Value - creationTime).TotalSeconds,
  295. options.SlidingExpiration.Value.TotalSeconds);
  296. }
  297. else if (absoluteExpiration.HasValue)
  298. {
  299. return (long)(absoluteExpiration.Value - creationTime).TotalSeconds;
  300. }
  301. else if (options.SlidingExpiration.HasValue)
  302. {
  303. return (long)options.SlidingExpiration.Value.TotalSeconds;
  304. }
  305. return null;
  306. }
  307. private static DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset creationTime, DistributedCacheEntryOptions options)
  308. {
  309. if (options.AbsoluteExpiration.HasValue && options.AbsoluteExpiration <= creationTime)
  310. {
  311. throw new ArgumentOutOfRangeException(
  312. nameof(DistributedCacheEntryOptions.AbsoluteExpiration),
  313. options.AbsoluteExpiration.Value,
  314. "The absolute expiration value must be in the future.");
  315. }
  316. var absoluteExpiration = options.AbsoluteExpiration;
  317. if (options.AbsoluteExpirationRelativeToNow.HasValue)
  318. {
  319. absoluteExpiration = creationTime + options.AbsoluteExpirationRelativeToNow;
  320. }
  321. return absoluteExpiration;
  322. }
  323. public void Dispose()
  324. {
  325. if (_connection != null)
  326. {
  327. _connection.Close();
  328. }
  329. }
  330. }
  331. }
  1. using Microsoft.Extensions.Options;
  2. namespace Microsoft.Extensions.Caching.Redis
  3. {
  4. /// <summary>
  5. /// Configuration options for <see cref="RedisCache"/>.
  6. /// </summary>
  7. public class RedisCacheOptions : IOptions<RedisCacheOptions>
  8. {
  9. /// <summary>
  10. /// The configuration used to connect to Redis.
  11. /// </summary>
  12. public string Configuration { get; set; }
  13. /// <summary>
  14. /// The Redis instance name.
  15. /// </summary>
  16. public string InstanceName { get; set; }
  17. RedisCacheOptions IOptions<RedisCacheOptions>.Value
  18. {
  19. get { return this; }
  20. }
  21. }
  22. }
  1. using System.Threading.Tasks;
  2. using StackExchange.Redis;
  3. namespace Microsoft.Extensions.Caching.Redis
  4. {
  5. internal static class RedisExtensions
  6. {
  7. private const string HmGetScript = (@"return redis.call('HMGET', KEYS[1], unpack(ARGV))");
  8. internal static RedisValue[] HashMemberGet(this IDatabase cache, string key, params string[] members)
  9. {
  10. var result = cache.ScriptEvaluate(
  11. HmGetScript,
  12. new RedisKey[] { key },
  13. GetRedisMembers(members));
  14. // TODO: Error checking?
  15. return (RedisValue[])result;
  16. }
  17. internal static async Task<RedisValue[]> HashMemberGetAsync(
  18. this IDatabase cache,
  19. string key,
  20. params string[] members)
  21. {
  22. var result = await cache.ScriptEvaluateAsync(
  23. HmGetScript,
  24. new RedisKey[] { key },
  25. GetRedisMembers(members));
  26. // TODO: Error checking?
  27. return (RedisValue[])result;
  28. }
  29. private static RedisValue[] GetRedisMembers(params string[] members)
  30. {
  31. var redisMembers = new RedisValue[members.Length];
  32. for (int i = 0; i < members.Length; i++)
  33. {
  34. redisMembers[i] = (RedisValue)members[i];
  35. }
  36. return redisMembers;
  37. }
  38. }
  39. }

配置启用Session

我们在Startup中ConfigureServices增加

  1. services.AddSingleton<IDistributedCache>(
  2. serviceProvider =>
  3. new RedisCache(new RedisCacheOptions
  4. {
  5. Configuration = "192.168.178.141:6379",
  6. InstanceName = "Sample:"
  7. }));
  8. services.AddSession();

在Startup中Configure增加

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

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

验证结果

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

  1. if (string.IsNullOrEmpty(HttpContext.Session.GetString("D")))
  2. {
  3. var d = DateTime.Now.ToString();
  4. HttpContext.Session.SetString("D", d);
  5. HttpContext.Response.ContentType = "text/plain";
  6. await HttpContext.Response.WriteAsync("Hello First timer///" + d);
  7. }
  8. else
  9. {
  10. HttpContext.Response.ContentType = "text/plain";
  11. await HttpContext.Response.WriteAsync("Hello old timer///" + HttpContext.Session.GetString("D"));
  12. }

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

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行