原文: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. @configuration和@component之间的区别

    @configuration和@component之间的区别是:@Component注解的范围最广,所有类都可以注解,但是@Configuration注解一般注解在这样的类上:这个类里面有@Value ...

  2. Linux编程之文件锁

    1. 使用 fcntl() 给记录加锁 使用 fcntl() 能够在一个文件的任意部分上放置一把锁,这个文件部分既可以是一个字节,也可以是整个文件.这种形式的文件加锁通常被称为记录加锁,但这种称谓是不 ...

  3. PHP AJAX 返回JSON 数据

    例子:利用AJAX返回JSON数据,间接访问数据库,查出Nation 表,并用下拉列表显示 造一个外部下拉列表框 </select> JQurey代码 $(document).ready( ...

  4. 发布机制-A/B 测试:百科

    ylbtech-发布机制-A/B 测试:百科 AB测试是为Web或App界面或流程制作两个(A/B)或多个(A/B/n)版本,在同一时间维度,分别让组成成分相同(相似)的访客群组(目标人群)随机的访问 ...

  5. 使用Statement执行DML和DQL语句

    import com.loaderman.util.JdbcUtil; import java.sql.Connection; import java.sql.DriverManager; impor ...

  6. 数据库开源框架之GreenDAO

    主页: https://github.com/greenrobot/greenDAO 配置: 添加以下依赖 * compile 'de.greenrobot:greendao:2.1.0' * com ...

  7. JMeter4.0以上 分布式测试报错 "server failed start Listen failed on port"

    使用JMeter4.0做分布式测试的是否,我的电脑作为肉鸡(执行机),双击jmeter-server.bat后显示失败 Found ApacheJMeter_core.jarUsing local p ...

  8. [java][转]安装ADT的时候,提示“Cannot complete the install because one or more required items could not be

    今天在安装ADT的时候,提示“Cannot complete the install because one or more required items could not be found.  S ...

  9. 关于 About

    关于我 我是 Ivy,目前武汉大学 GIS 专业在读硕士研究生,业余渣程序媛. 写了一些不起眼的代码(参看我的 GitHub),做了一些不起眼的小研究(参看我的 ResearchGate). 关于本站 ...

  10. EL表达式与JSTL标签库(二)

    1.JSTL标签库 标签库 作用 URI 前缀 核心 包含Web应用的常见工作,如循环.输入输出等 http://java.sun.com/jsp/jstl/core c 国际化 语言区域.消息.数字 ...