欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用Asp.Net Core MVC 开发项目实践[第五篇:缓存的使用]

程序员文章站 2022-08-10 10:59:01
项目中我们常常会碰到一些数据,需要高频率用到但是又不会频繁变动的这类,我们就可以使用缓存把这些数据缓存起来(比如说本项目的导航数据,帖子频道数据). 我们项目中常用到有Asp.Net Core 本身提供的缓存组件MemoryCache以及第三方缓存组件Redis(当然这个不仅仅只用来做缓存工具用). ......

项目中我们常常会碰到一些数据,需要高频率用到但是又不会频繁变动的这类,我们就可以使用缓存把这些数据缓存起来(比如说本项目的导航数据,帖子频道数据).

我们项目中常用到有asp.net core 本身提供的缓存组件memorycache以及第三方缓存组件redis(当然这个不仅仅只用来做缓存工具用).

memorycache组件的使用:

第一步:我们在startup类中configureservices方法中添加缓存组件

services.addmemorycache();

第二步:我们就可以在项目中使用该缓存组件了

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.mvc;
using microsoft.extensions.caching.memory;
using mvcdemo.core.cache;
namespace mvcdemo.web.controllers
{
    public class cachecontroller : controller
    {
        imemorycache _cache = null;
        public cachecontroller(imemorycache memorycache)
        {
            _cache = memorycache;
        }
        public iactionresult index()
        {
            //memorycache示例
            string memorycache = _cache.get<string>("memorycachetest");
            if (string.isnullorempty(memorycache))
            {
                //添加并且设置缓存
                _cache.set<string>("memorycachetest", "我是memorycachetest缓存");
                memorycache = _cache.get<string>("memorycachetest");
            }
            viewdata["memorycache"] = memorycache;
            return view();
        }
    }
}

ps:在这里我们使用的构造函数注入的方式获取到了memorycache的实例对象

redis缓存组件的使用:

ps:我们使用的是windows系统上安装的redis组件,安装教程请查看https://www.51core.net/posts/read/3048

第一步:使用nuget添加microsoft.extensions.caching.redis组件

使用Asp.Net Core MVC 开发项目实践[第五篇:缓存的使用]

第二步:将redis常用方法封装成一个服务

1.创建一个icacheservice的接口,方便缓存组件的扩展

 

 1 using system;
 2 using system.collections.generic;
 3 using system.text;
 4 
 5 namespace mango.framework.services.cache
 6 {
 7     public interface icacheservice
 8     {
 9         /// <summary>
10         /// 获取缓存
11         /// </summary>
12         /// <typeparam name="t">泛型(返回的结果类型)</typeparam>
13         /// <param name="key">缓存key</param>
14         /// <returns></returns>
15         t get<t>(string key) where t : new();
16         /// <summary>
17         /// 获取缓存
18         /// </summary>
19         /// <param name="key">缓存key</param>
20         /// <returns></returns>
21         string get(string key);
22         /// <summary>
23         /// 添加缓存
24         /// </summary>
25         /// <param name="key">缓存key</param>
26         /// <param name="value">缓存值</param>
27         /// <param name="expirationtime">绝对过期时间(分钟)</param>
28         void add(string key, object value, int expirationtime = 20);
29         /// <summary>
30         /// 移除缓存
31         /// </summary>
32         /// <param name="key"></param>
33         void remove(string key);
34         /// <summary>
35         /// 更新缓存
36         /// </summary>
37         /// <param name="key"></param>
38         /// <param name="value"></param>
39         /// <param name="expirationtime"></param>
40         void replace(string key, object value, int expirationtime = 20);
41     }
42 }

2.创建一个rediscacheservice类继承自icacheservice接口并且实现接口中的方法

using system;
using system.text;
using microsoft.extensions.caching.redis;
using microsoft.extensions.caching.distributed;
using newtonsoft.json;
namespace mango.framework.services.cache
{
    public class rediscacheservice:icacheservice
    {
        private rediscache _rediscache = null;
        public rediscacheservice(rediscacheoptions options)
        {
            _rediscache = new rediscache(options);
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="t">泛型(返回的结果类型)</typeparam>
        /// <param name="key">缓存key</param>
        /// <returns></returns>
        public t get<t>(string key) where t:new()
        {
            try
            {
                if (!string.isnullorempty(key))
                {
                    return jsonconvert.deserializeobject<t>(encoding.utf8.getstring(_rediscache.get(key)));
                }
                return default(t);
            }
            catch
            {
                return default(t);
            }
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">缓存key</param>
        /// <returns></returns>
        public string get(string key)
        {
            try
            {
                if (!string.isnullorempty(key))
                {
                    return encoding.utf8.getstring(_rediscache.get(key));
                }
                return string.empty;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存key</param>
        /// <param name="value">缓存值</param>
        /// <param name="expirationtime">绝对过期时间(分钟)</param>
        public void add(string key,object value,int expirationtime=20)
        {
            if (!string.isnullorempty(key))
            {
                _rediscache.set(key, encoding.utf8.getbytes(jsonconvert.serializeobject(value)), new distributedcacheentryoptions()
                {
                    absoluteexpiration = datetimeoffset.now.addminutes(expirationtime)
                });
            }
        }
        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key">缓存key</param>
        public void remove(string key)
        {
            if (!string.isnullorempty(key))
            {
                _rediscache.remove(key);
            }
        }
        /// <summary>
        /// 更新缓存
        /// </summary>
        /// <param name="key">缓存key</param>
        /// <param name="value">缓存值</param>
        /// <param name="expirationtime"></param>
        public void replace(string key, object value, int expirationtime = 20)
        {
            if (!string.isnullorempty(key))
            {
                _rediscache.remove(key);
                _rediscache.set(key, encoding.utf8.getbytes(jsonconvert.serializeobject(value)), new distributedcacheentryoptions()
                {
                    absoluteexpiration = datetimeoffset.now.addminutes(expirationtime)
                });
            }
        }
    }
}

ps:该类中的构造函数负责创建redis缓存的实例并且把相关的参数(连接字符串)传入进行连接

第三步:在startup类中configureservices添加封装的服务组件

//注册自定义服务
services.addsingleton(typeof(icacheservice), new rediscacheservice(new rediscacheoptions()
{
      configuration = configuration.getsection("cache:connectionstring").value,
      instancename = configuration.getsection("cache:instancename").value
}));
//注册到全局服务控制类中以供其它项目的使用
framework.services.servicecontext.registerservices(services);

第四步:在项目中调用,示例代码如下

icacheservice cacheservice = servicecontext.getservice<icacheservice>();
string cachedata = cacheservice.get("websiteconfigcache");

到此asp.net core mvc项目中缓存的使用介绍已经完成.