项目中我们常常会碰到一些数据,需要高频率用到但是又不会频繁变动的这类,我们就可以使用缓存把这些数据缓存起来(比如说本项目的导航数据,帖子频道数据).
我们项目中常用到有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组件
第二步:将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项目中缓存的使用介绍已经完成.