栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

我们项目中常用到有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("memoryCacheTest");            if (string.IsNullOrEmpty(memoryCache))
            {                //添加并且设置缓存
                _cache.Set("memoryCacheTest", "我是memoryCacheTest缓存");
                memoryCache = _cache.Get("memoryCacheTest");
            }
            ViewData["memoryCache"] = memoryCache;            return View();
        }
    }
}

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

Redis缓存组件的使用:

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

第一步:使用Nuget添加Microsoft.Extensions.Caching.Redis组件

第二步:将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         /// 10         /// 获取缓存11         /// 12         /// 泛型(返回的结果类型)13         /// 缓存key14         /// 15         T Get(string key) where T : new();16         /// 17         /// 获取缓存18         /// 19         /// 缓存key20         /// 21         string Get(string key);22         /// 23         /// 添加缓存24         /// 25         /// 缓存key26         /// 缓存值27         /// 绝对过期时间(分钟)28         void Add(string key, object value, int expirationTime = 20);29         /// 30         /// 移除缓存31         /// 32         /// 33         void Remove(string key);34         /// 35         /// 更新缓存36         /// 37         /// 38         /// 39         /// 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);
        }        /// 
        /// 获取缓存        /// 
        /// 泛型(返回的结果类型)
        /// 缓存key
        /// 
        public T Get(string key) where T:new()
        {            try
            {                if (!string.IsNullOrEmpty(key))
                {                    return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(_redisCache.Get(key)));
                }                return default(T);
            }            catch
            {                return default(T);
            }
        }        /// 
        /// 获取缓存        /// 
        /// 缓存key
        /// 
        public string Get(string key)
        {            try
            {                if (!string.IsNullOrEmpty(key))
                {                    return Encoding.UTF8.GetString(_redisCache.Get(key));
                }                return string.Empty;
            }            catch
            {                return null;
            }
        }        /// 
        /// 添加缓存        /// 
        /// 缓存key
        /// 缓存值
        /// 绝对过期时间(分钟)
        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)
                });
            }
        }        /// 
        /// 移除缓存        /// 
        /// 缓存key
        public void Remove(string key)
        {            if (!string.IsNullOrEmpty(key))
            {
                _redisCache.Remove(key);
            }
        }        /// 
        /// 更新缓存        /// 
        /// 缓存key
        /// 缓存值
        /// 
        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();string cacheData = cacheService.Get("WebSiteConfigCache");

到此ASP.NET CORE MVC项目中缓存的使用介绍已经完成.

作者:喻平勇

原文出处:https://www.cnblogs.com/51core/p/10445487.html  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/230732.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号