zoukankan      html  css  js  c++  java
  • Net core 关于缓存的实现

    在很多项目中, 需要用到缓存,借鉴网上前辈们的一些经验,自己再进行总结简化了一些, 做出如下的缓存操作,其中包含内存缓存(IMemoryCache) 和 Redis 缓存;

    一.前提内容, 导入两个包:  Microsoft.Extensions.Caching.Memory   和 Microsoft.Extensions.Caching.Redis ,并在使用的类中using 一下它们.  我这里是用2.1.0版本的; 

    二. 创建 ICacheService 公共接口 ,我这里写的比较简单, 如若业务需要可自行增加 异步和批量的接口方法.

     1 /// <summary>
     2     /// 缓存接口
     3     /// 分别内存缓存和Redis缓存(2.1.0版本)
     4     /// </summary>
     5     public interface ICacheService
     6     { 
     7         /// <summary>
     8         ///  新增
     9         /// </summary>
    10         /// <param name="key"></param>
    11         /// <param name="value"></param>
    12         /// <param name="ExpirtionTime"></param>
    13         /// <returns></returns>
    14         bool Add(string key, object value, int ExpirtionTime = 20);
    15 
    16 
    17         /// <summary>
    18         /// 获取
    19         /// </summary>
    20         /// <param name="key"></param>
    21         /// <returns></returns>
    22         string GetValue(string key);
    23         /// <summary>
    24         /// 验证缓存项是否存在
    25         /// </summary>
    26         /// <param name="key">缓存Key</param>
    27         /// <returns></returns>
    28         bool Exists(string key);
    29 
    30         /// <summary>
    31         /// 移除
    32         /// </summary>
    33         /// <param name="key"></param>
    34         /// <returns></returns>
    35         bool Remove(string key);
    36     }

    三. 再分别创建 MemoryCacheService 和RedisCacheService  类, 并继承 ICacheService 接口.

    a.  MemoryCacheService  类  , 记得using 一下 Microsoft.Extensions.Caching.Memory

     /// <summary>
        /// 缓存接口实现
        /// </summary>
        public class MemoryCacheService : ICacheService
        {
            protected IMemoryCache _cache;
    
            public MemoryCacheService(IMemoryCache cache)
            {
                _cache = cache;
            }
             
            public bool Add(string key, object value, int ExpirtionTime = 20)
            {
                if (!string.IsNullOrEmpty(key))
                {
                    _cache.Set(key, value , DateTimeOffset.Now.AddMinutes(ExpirtionTime));
                }
                return true;
            }
    
            public bool Remove(string key)
            {
                if (string.IsNullOrEmpty(key))
                {
                    return false;
                }
                if (Exists(key))
                {
                    _cache.Remove(key);
                    return true;
                }
                return false;
            }
             
            public string GetValue(string key)
            {
                if (string.IsNullOrEmpty(key))
                {
                    return null;
                }
                if (Exists(key))
                {
                    return _cache.Get(key).ToString();
                }
                return null;
            }
             
            public bool Exists(string key)
            {
                if (string.IsNullOrEmpty(key))
                {
                    return false;
                }
    
                object cache;
                return _cache.TryGetValue(key, out cache);
            }
             
        }
    View Code

    b. RedisCacheService 类  , 记得using 一下 Microsoft.Extensions.Caching.Redis

    public  class RedisCacheService:ICacheService
        {
            protected RedisCache _redisCache = null;
    
            public RedisCacheService(RedisCacheOptions options)
            {
                _redisCache = new RedisCache(options);
            }
             
    
             
            public bool Add(string key, object value,int ExpirtionTime=20)
            {
                if (!string.IsNullOrEmpty(key))
                {
                    _redisCache.Set(key, Encoding.UTF8.GetBytes(value.ToString()), new DistributedCacheEntryOptions()
                    {
                        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(ExpirtionTime)
                    });
                }
                return true; 
            }
    
            public bool Remove(string key)
            {
                if (string.IsNullOrEmpty(key))
                {
                    return false;
                }
    
                if (Exists(key))
                {
                    _redisCache.Remove(key);
                    return true;
                } 
                return false;
            }
    
    
            public string GetValue(string key)
            {
                if (string.IsNullOrEmpty(key))
                {
                    return null;
                }
                if (Exists(key))
                {
                    return _redisCache.GetString(key);
                }
                return null;
            }
    
    
            public bool Exists(string key)
            {
                if (string.IsNullOrEmpty(key))
                {
                    return false;
                }
              return  !string.IsNullOrEmpty(_redisCache.GetString(key)) ? true :false;
            }
            
        }
    View Code

    四.  在 Startup.cs  文件中注入 Redis 和Memory.  这里啰嗦多几句, 因为同一个接口注入了多个实现,  那到调用的时候, 容器是怎么知道调用哪个类呢?   我这里是参考了  

    ASP.NET Core默认注入方式下如何注入多个实现(多种方式)  ,  

                services.AddTransient<MemoryCacheService>(); //内存缓存认证注入 
                //注入Redis
                services.AddSingleton(new RedisCacheService(new RedisCacheOptions()
                {
                    InstanceName = Configuration.GetSection("Redis:InstanceName").Value,
                    Configuration= Configuration.GetSection("Redis:Connection").Value
                }));

    并在appsettings.json配置redis , 

     "Redis": {
        "Connection": "127.0.0.1:6379",
        "InstanceName": "Redis:"
      }

    服务调用我使用了IServiceProvider  .

    调用如下: 

     五.总结   

    总算是写了一篇让自己看得懂一些的文章了.   行吧...算是一个小进步吧!

  • 相关阅读:
    MFC对话框编程详细学习笔记
    VS2013 MFC基于对话框编程
    Java学到什么程度可以找到第一份工作
    搞定操作系统面试,看这篇就够了
    搞定计算机网络面试,看这篇就够了
    一千行 MySQL 学习笔记
    后端工程师技术面试复习大纲
    爬虫功能
    昨天的一卦,真的太形象,可惜我就是不敢断
    基于maven+ssm的增删改查之批量删除
  • 原文地址:https://www.cnblogs.com/mylinx/p/10443494.html
Copyright © 2011-2022 走看看