原文:ASP.NET CORE CACHE的使用(含MemoryCache,Redis)

版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。

依赖命名空间:

Microsoft.AspNetCore.Mvc;//测试调用时

Microsoft.Extensions.Caching.Memory;

Microsoft.Extensions.Caching.Redis;

StackExchange.Redis;

Newtonsoft.Json;

定义通用工具类 :CacheUntity

public class CacheUntity

    {

        private static ICacheHelper _cache = new RedisCacheHelper();//默认使用Redis

        private static bool isInited = false;

        public static void Init(ICacheHelper cache)

        {

            if (isInited)

                return;

            _cache.Dispose();

            _cache = cache;

            isInited = true;

        }

        public static bool Exists(string key)

        {

            return _cache.Exists(key);

        }

        public static T GetCache<T>(string key) where T : class

        {

            return _cache.GetCache<T>(key);

        }

        public static void SetCache(string key, object value)

        {

            _cache.SetCache(key, value);

        }

        public static void SetCache(string key, object value, DateTimeOffset expiressAbsoulte)

        {

            _cache.SetCache(key, value, expiressAbsoulte);

        }

        //public void SetCache(string key, object value, double expirationMinute)

        //{

        //}

        public static void RemoveCache(string key)

        {

            _cache.RemoveCache(key);

        }

    }

定义统一缓存操作接口:ICacheHelper

public interface ICacheHelper

    {

        bool Exists(string key);

        T GetCache<T>(string key) where T : class;

        void SetCache(string key, object value);

        void SetCache(string key, object value, DateTimeOffset expiressAbsoulte);//设置绝对时间过期

        //void SetCache(string key, object value, double expirationMinute);  //设置滑动过期, 因redis暂未找到自带的滑动过期类的API,暂无需实现该接口

        void RemoveCache(string key);

        void Dispose();

    }

定义RedisCache帮助类:RedisCacheHelper

public class RedisCacheHelper : ICacheHelper

    {

        public RedisCacheHelper(/*RedisCacheOptions options, int database = 0*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把连接信息直接写在帮助类里

        {

            RedisCacheOptions options = new RedisCacheOptions();

            options.Configuration = "127.0.0.1:6379";

            options.InstanceName = "test";

            int database = 0;

            _connection = ConnectionMultiplexer.Connect(options.Configuration);

            _cache = _connection.GetDatabase(database);

            _instanceName = options.InstanceName;

        }

        private IDatabase _cache;

        private ConnectionMultiplexer _connection;

        private readonly string _instanceName;

        private string GetKeyForRedis(string key)

        {

            return _instanceName + key;

        }

        public bool Exists(string key)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            return _cache.KeyExists(GetKeyForRedis(key));

        }

        public T GetCache<T>(string key) where T : class

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            var value = _cache.StringGet(GetKeyForRedis(key));

            if (!value.HasValue)

                return default(T);

            return JsonConvert.DeserializeObject<T>(value);

        }

        public void SetCache(string key, object value)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            if (value == null)

                throw new ArgumentNullException(nameof(value));

            if (Exists(GetKeyForRedis(key)))

                RemoveCache(GetKeyForRedis(key));

            _cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value));

        }

        public void SetCache(string key, object value, DateTimeOffset expiressAbsoulte)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            if (value == null)

                throw new ArgumentNullException(nameof(value));

            if (Exists(GetKeyForRedis(key)))

                RemoveCache(GetKeyForRedis(key));

            _cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value), expiressAbsoulte - DateTime.Now);

        }

        //public void SetCache(string key, object value, double expirationMinute)

        //{

        //    if (Exists(GetKeyForRedis(key)))

        //        RemoveCache(GetKeyForRedis(key));

        //    DateTime now = DateTime.Now;

        //    TimeSpan ts = now.AddMinutes(expirationMinute) - now;

        //    _cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value), ts);

        //}

        public void RemoveCache(string key)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            _cache.KeyDelete(GetKeyForRedis(key));

        }

        public void Dispose()

        {

            if (_connection != null)

                _connection.Dispose();

            GC.SuppressFinalize(this);

        }

    }

定义MemoryCache帮助类:MemoryCacheHelper

public class MemoryCacheHelper : ICacheHelper

    {

        public MemoryCacheHelper(/*MemoryCacheOptions options*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把选项直接封在帮助类里边

        {

            //this._cache = new MemoryCache(options);

            this._cache = new MemoryCache(new MemoryCacheOptions());

        }

        private IMemoryCache _cache;

        public bool Exists(string key)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            object v = null;

            return this._cache.TryGetValue<object>(key, out v);

        }

        public T GetCache<T>(string key) where T : class

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            T v = null;

            this._cache.TryGetValue<T>(key, out v);

            return v;

        }

        public void SetCache(string key, object value)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            if (value == null)

                throw new ArgumentNullException(nameof(value));

            object v = null;

            if (this._cache.TryGetValue(key, out v))

                this._cache.Remove(key);

            this._cache.Set<object>(key, value);

        }

        public void SetCache(string key, object value, double expirationMinute)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            if (value == null)

                throw new ArgumentNullException(nameof(value));

            object v = null;

            if (this._cache.TryGetValue(key, out v))

                this._cache.Remove(key);

            DateTime now = DateTime.Now;

            TimeSpan ts = now.AddMinutes(expirationMinute) - now;

            this._cache.Set<object>(key, value, ts);

        }

        public void SetCache(string key, object value, DateTimeOffset expirationTime)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            if (value == null)

                throw new ArgumentNullException(nameof(value));

            object v = null;

            if (this._cache.TryGetValue(key, out v))

                this._cache.Remove(key);

            this._cache.Set<object>(key, value, expirationTime);

        }

        public void RemoveCache(string key)

        {

            if (string.IsNullOrWhiteSpace(key))

                throw new ArgumentNullException(nameof(key));

            this._cache.Remove(key);

        }

        public void Dispose()

        {

            if (_cache != null)

                _cache.Dispose();

            GC.SuppressFinalize(this);

        }

    }

调用:

[HttpGet]

        public string TestCache()

        {

            CacheUntity.SetCache("test", "RedisCache works!");

            string res = CacheUntity.GetCache<string>("test");

            res += Environment.NewLine;

            CacheUntity.Init(new MemoryCacheHelper());

            CacheUntity.SetCache("test", "MemoryCache works!");

            res += CacheUntity.GetCache<string>("test");

            return res;

        }

ASP.NET CORE CACHE的使用(含MemoryCache,Redis)的更多相关文章

  1. 在ASP.NET Core 2.0中使用MemoryCache

    说到内存缓存大家可能立马想到了HttpRuntime.Cache,它位于System.Web命名空间下,但是在ASP.NET Core中System.Web已经不复存在.今儿个就简单的聊聊如何在ASP ...

  2. 第十二节:Asp.Net Core 之分布式缓存(SQLServer和Redis)

    一. 整体说明 1. 说明 分布式缓存通常是指在多个应用程序服务器的架构下,作为他们共享的外部服务共享缓存,常用的有SQLServer.Redis.NCache.     特别说明一下:这里的分布式是 ...

  3. asp.net core计划任务探索之hangfire+redis+cluster

    研究了一整天的quartz.net,发现一直无法解决cluster模式下多个node独立运行的问题,改了很多配置项,仍然是每个node各自为战.本来cluster模式下的各个node应该是负载均衡的, ...

  4. 记一次使用Asp.Net Core WebApi 5.0+Dapper+Mysql+Redis+Docker的开发过程

    #前言 我可能有三年没怎么碰C#了,目前的工作是在全职搞前端,最近有时间抽空看了一下Asp.net Core,Core版本号都到了5.0了,也越来越好用了,下面将记录一下这几天以来使用Asp.Net ...

  5. ASP.NET Core中的缓存[1]:如何在一个ASP.NET Core应用中使用缓存

    .NET Core针对缓存提供了很好的支持 ,我们不仅可以选择将数据缓存在应用进程自身的内存中,还可以采用分布式的形式将缓存数据存储在一个“中心数据库”中.对于分布式缓存,.NET Core提供了针对 ...

  6. asp.net core 系列之Response caching(1)

    这篇文章简单的讲解了response caching: 讲解了cache-control,及对其中的头和值的作用,及设置来控制response caching; 简单的罗列了其他的缓存技术:In-me ...

  7. 从零搭建一个IdentityServer——集成Asp.net core Identity

    前面的文章使用Asp.net core 5.0以及IdentityServer4搭建了一个基础的验证服务器,并实现了基于客户端证书的Oauth2.0授权流程,以及通过access token访问被保护 ...

  8. asp.net core 实战之 redis 负载均衡和"高可用"实现

    1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的"高可用"实现, 呵呵双引号的"高可用"并不是 ...

  9. 简易的开发框架(微服务) Asp.Net Core 2.0

      Asp.Net Core 2.0 + Mysql Orm + Ioc + Redis + AOP + RabbitMQ + Etcd + Autofac + Swagger 基础框架: https ...

随机推荐

  1. BeanFactory和ApplicationContext的区别+部分Spring的使用

    BeanFactory和ApplicationContext的区别 ApplicationContext 方式加载:创建容器的同时 容器初始化,容器所有的bean创建完毕   Spring容器中获取一 ...

  2. Linux远程连接工具 Shell Xshell6 XFtp6 绿色破解免安装版

    百度云下载链接: https://pan.baidu.com/s/1HMkuxv1yaAM1yhtz09zpfQ 关注以下公众号,回复xshell,获取提取码 关注公众号githubcn,免费获取更多 ...

  3. Java-JVM 类加载机制

    类的生命周期中的第一步,就是要被 JVM 加载进内存,类加载器就是来干这件事. 一.类加载器种类 系统提供了 3 种类加载器: 1.启动类加载器(Bootstrap ClassLoader) 由 C ...

  4. python sqlalchemy 进行 mysql 数据库操作

    1. 进行mysql数据库的创建,如果已经存在,就相当于进行数据库的连接操作 from sqlalchemy import create_engine from sqlalchemy.ext.decl ...

  5. 转 Golang 入门 : 切片(slice)

    https://www.jianshu.com/p/354fce23b4f0 切片(slice)是 Golang 中一种比较特殊的数据结构,这种数据结构更便于使用和管理数据集合.切片是围绕动态数组的概 ...

  6. js获取当前日期并格式yyy-MM-dd

    //格式化日期:yyyy-MM-dd function formatDate(date) { var myyear = date.getFullYear(); var mymonth = date.g ...

  7. [go]go并发

    同步协程 通过睡眠方法 // 通过睡眠方式等待 time.Sleep(time.Second) <-time.NewTimer(time.Second).C <-time.After(ti ...

  8. 依赖注入框架之androidannotations

    主页: http://androidannotations.org/ 用途: 1. 使用依赖注入Views,extras,System Service,resources 2. 简化线程模型 3. 事 ...

  9. js前台传数组,java后台接收转list,前后台用正则校验

    前台,传参数时,将数组对象转换成json串,后台java收到后用 JSONArray.fromObject 转成集合. 前台js:var params = {"FileNameList&qu ...

  10. 美化Eclipse-背景

    为了美化Eclipse,请登录主题网站http://www.eclipsecolorthemes.org/ 下载EPF配置文件(截图如下),并导入eclispe即可. 导入方法: (1)从File菜单 ...