解读ASP.NET 5 & MVC6系列教程(8):Session与Caching(2)

该接口是缓存Caching的通用接口,也就是说,只要我们实现了缓存接口,就可以将其用于Session的管理。进一步查看该接口发现,该接口中定义的Set方法还需要实现一个ICacheContext类型的缓存上下文(以便在调用的时候让其它程序进行委托调用),接口定义分别如下:

public interface IDistributedCache { void Connect(); void Refresh(string key); void Remove(string key); Stream Set(string key, object state, Action<ICacheContext> create); bool TryGetValue(string key, out Stream value); } public interface ICacheContext { Stream Data { get; } string Key { get; } object State { get; } void SetAbsoluteExpiration(TimeSpan relative); void SetAbsoluteExpiration(DateTimeOffset absolute); void SetSlidingExpiration(TimeSpan offset); }

接下来,我们基于Redis来实现上述功能,创建RedisCache类,并继承IDistributedCache,引用StackExchange.Redis程序集,然后实现IDistributedCache接口的所有方法和属性,代码如下:

using Microsoft.Framework.Cache.Distributed; using Microsoft.Framework.OptionsModel; using StackExchange.Redis; using System; using System.IO; namespace Microsoft.Framework.Caching.Redis { public class RedisCache : IDistributedCache { // KEYS[1] = = key // ARGV[1] = absolute-expiration - ticks as long (-1 for none) // ARGV[2] = sliding-expiration - ticks as long (-1 for none) // ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration) // ARGV[4] = data - byte[] // this order should not change LUA script depends on it private const string SetScript = (@" redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4]) if ARGV[3] ~= '-1' then redis.call('EXPIRE', KEYS[1], ARGV[3]) end return 1"); private const string AbsoluteExpirationKey = "absexp"; private const string SlidingExpirationKey = "sldexp"; private const string DataKey = "data"; private const long NotPresent = -1; private ConnectionMultiplexer _connection; private IDatabase _cache; private readonly RedisCacheOptions _options; private readonly string _instance; public RedisCache(IOptions<RedisCacheOptions> optionsAccessor) { _options = optionsAccessor.Options; // This allows partitioning a single backend cache for use with multiple apps/services. _instance = _options.InstanceName ?? string.Empty; } public void Connect() { if (_connection == null) { _connection = ConnectionMultiplexer.Connect(_options.Configuration); _cache = _connection.GetDatabase(); } } public Stream Set(string key, object state, Action<ICacheContext> create) { Connect(); var context = new CacheContext(key) { State = state }; create(context); var value = context.GetBytes(); var result = _cache.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key }, new RedisValue[] { context.AbsoluteExpiration?.Ticks ?? NotPresent, context.SlidingExpiration?.Ticks ?? NotPresent, context.GetExpirationInSeconds() ?? NotPresent, value }); // TODO: Error handling return new MemoryStream(value, writable: false); } public bool TryGetValue(string key, out Stream value) { value = GetAndRefresh(key, getData: true); return value != null; } public void Refresh(string key) { var ignored = GetAndRefresh(key, getData: false); } private Stream GetAndRefresh(string key, bool getData) { Connect(); // This also resets the LRU status as desired. // TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math. RedisValue[] results; if (getData) { results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey); } else { results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey); } // TODO: Error handling if (results.Length >= 2) { // Note we always get back two results, even if they are all null. // These operations will no-op in the null scenario. DateTimeOffset? absExpr; TimeSpan? sldExpr; MapMetadata(results, out absExpr, out sldExpr); Refresh(key, absExpr, sldExpr); } if (results.Length >= 3 && results[2].HasValue) { return new MemoryStream(results[2], writable: false); } return null; } private void MapMetadata(RedisValue[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration) { absoluteExpiration = null; slidingExpiration = null; var absoluteExpirationTicks = (long?)results[0]; if (absoluteExpirationTicks.HasValue && absoluteExpirationTicks.Value != NotPresent) { absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks.Value, TimeSpan.Zero); } var slidingExpirationTicks = (long?)results[1]; if (slidingExpirationTicks.HasValue && slidingExpirationTicks.Value != NotPresent) { slidingExpiration = new TimeSpan(slidingExpirationTicks.Value); } } private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr) { // Note Refresh has no effect if there is just an absolute expiration (or neither). TimeSpan? expr = null; if (sldExpr.HasValue) { if (absExpr.HasValue) { var relExpr = absExpr.Value - DateTimeOffset.Now; expr = relExpr <= sldExpr.Value ? relExpr : sldExpr; } else { expr = sldExpr; } _cache.KeyExpire(_instance + key, expr); // TODO: Error handling } } public void Remove(string key) { Connect(); _cache.KeyDelete(_instance + key); // TODO: Error handling } } }

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

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