Net Core 缓存系列:

    1、NetCore IMemoryCache 内存缓存

    2、Distributed Cache(分布式缓存)-SqlServer

    3、Distributed Cache(分布式缓存)-Redis

欢迎交流学习!!! GitHub源码

Asp.NET Core 官网目前支持的分布式缓存主要有Sql Server, Redis 和NCache,Sql Server的分布式安装及使用已在上篇文章记录 Distributed Cache(分布式缓存)-SqlServer ,NCache会在接下里的文章中提及。

Redis使用

1、将redis service 添加到Services请求管道中:

 services.AddDistributedRedisCache(options =>
 {
       options.Configuration = $"{configuration["RedisDistributedCache:IPAddress"]}:{configuration["RedisDistributedCache:Port"]},password={configuration["RedisDistributedCache:Password"]}";
       options.InstanceName = configuration["RedisDistributedCache:InstanceName"];
 });

appsettings.json配置文件如下:

"RedisDistributedCache": {
    "IPAddress": "127.0.0.1",
    "Port": "6379",
    "Password": "demo12!@",
    "InstanceName": "DistributedCache.Redis"
  }

2、根据业务需要封装IDistributedCache service,当然这里完全可以使用原生IDistributedCache, 直接通过构造函数依赖注入即可用。

提供必要的SetAsync / GetAsync接口实现,示例代码如下:

    public class RedisService : IDistributedService
    {
        private readonly IDistributedCache _cacheService;

        public RedisService(IDistributedCache cacheService)
        {
            this._cacheService = cacheService;
        }

        public async Task<T> GetAsync<T>(string key)
        {
            T obj = default(T);
            var value = await _cacheService.GetStringAsync(key);
            if (string.IsNullOrEmpty(value))
            { 
                return default(T);
            }
            try
            {
                obj = JsonConvert.DeserializeObject<T>(value);
            }
            catch (Exception ex)
            {
                throw new NotSupportedException(ex.Message, ex);
            }
            return obj;
        }

        public async Task<byte[]> GetAsync(string key)
        {
            return await _cacheService.GetAsync(key);
        }

        public async Task<string> GetStringAsync(string key)
        {
            return await _cacheService.GetStringAsync(key);
        }

        public async Task RefreshAsync(string key)
        {
            await _cacheService.RefreshAsync(key);
        }

        public async Task RemoveAsync(string key)
        {
            await _cacheService.RemoveAsync(key);
        }

        public async Task SetAsync(string key, object value, object expiration = null, bool isAbsoluteExpiration = false)
        {
            var jsonValue = string.Empty;
            try
            {
                jsonValue = JsonConvert.SerializeObject(value);
                var options = this.BuildDistributedCacheEntryOptions(expiration, isAbsoluteExpiration);
                await _cacheService.SetStringAsync(key, jsonValue, options);
            }
            catch (Exception ex)
            {
                throw new NotSupportedException(ex.Message, ex);
            }
        }

        public async Task SetAsync(string key, byte[] value, object expiration = null, bool isAbsoluteExpiration = false)
        {
            var options = this.BuildDistributedCacheEntryOptions(expiration, isAbsoluteExpiration);
            await _cacheService.SetAsync(key, value, options);
        }

        private DistributedCacheEntryOptions BuildDistributedCacheEntryOptions(object expiration = null, bool isAbsoluteExpiration = false)
        {
            var options = new DistributedCacheEntryOptions();
            if (expiration != null)
            {
                if (expiration is TimeSpan)
                {
                    if (isAbsoluteExpiration)
                        options.SetAbsoluteExpiration((TimeSpan)expiration);
                    else
                        options.SetSlidingExpiration((TimeSpan)expiration);
                }
                else if (expiration is DateTimeOffset)
                {
                    options.SetAbsoluteExpiration((DateTimeOffset)expiration);
                }
                else
                {
                    throw new NotSupportedException("Not support current expiration object settings.");
                }
            }
            return options;
        }
    }
View Code

相关文章: