.NET 8 下面的几种缓存的使用。
(1)ICache.cs
using System;
using System.Threading.Tasks;
public interface ICache { #region 设置缓存 /// <summary> /// 设置缓存 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">值</param> void Set(string key, object value); /// <summary> /// 设置缓存 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">值</param> Task SetAsync(string key, object value); /// <summary> /// 设置缓存 /// 注:默认过期类型为绝对过期 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">值</param> /// <param name="timeout">过期时间间隔</param> void Set(string key, object value, TimeSpan timeout); /// <summary> /// 设置缓存 /// 注:默认过期类型为绝对过期 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">值</param> /// <param name="timeout">过期时间间隔</param> Task SetAsync(string key, object value, TimeSpan timeout); /// <summary> /// 设置缓存 /// 注:默认过期类型为绝对过期 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">值</param> /// <param name="timeout">过期时间间隔</param> /// <param name="expireType">过期类型</param> void Set(string key, object value, TimeSpan timeout, ExpireType expireType); /// <summary> /// 设置缓存 /// 注:默认过期类型为绝对过期 /// </summary> /// <param name="key">缓存Key</param> /// <param name="value">值</param> /// <param name="timeout">过期时间间隔</param> /// <param name="expireType">过期类型</param> Task SetAsync(string key, object value, TimeSpan timeout, ExpireType expireType); #endregion #region 获取缓存 /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存Key</param> string Get(string key); /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存Key</param> Task<string> GetAsync(string key); /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存Key</param> T Get<T>(string key); /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存Key</param> Task<T> GetAsync<T>(string key); #endregion #region 删除缓存 /// <summary> /// 清除缓存 /// </summary> /// <param name="key">缓存Key</param> void Remove(string key); /// <summary> /// 清除缓存 /// </summary> /// <param name="key">缓存Key</param> Task RemoveAsync(string key); #endregion #region 刷新缓存 /// <summary> /// 刷新缓存 /// </summary> /// <param name="key">缓存Key</param> void Refresh(string key); /// <summary> /// 刷新缓存 /// </summary> /// <param name="key">缓存Key</param> Task RefreshAsync(string key); #endregion }
(2)CacheHelper.cs
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;
public class CacheHelper : ICache { readonly IDistributedCache _cache; public CacheHelper(IDistributedCache cache) { _cache = cache; } protected string BuildKey(string idKey) { return $"Cache_{GetType().FullName}_{idKey}"; } public void Set(string key, object value) { _cache.SetString(BuildKey(key), JsonHelper.SerializeObject(value)); } public async Task SetAsync(string key, object value) { await _cache.SetStringAsync(BuildKey(key), JsonHelper.SerializeObject(value)); } public void Set(string key, object value, TimeSpan timeout) { _cache.SetString(BuildKey(key), JsonHelper.SerializeObject(value), new DistributedCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout) }); } public async Task SetAsync(string key, object value, TimeSpan timeout) { await _cache.SetStringAsync(BuildKey(key), JsonHelper.SerializeObject(value), new DistributedCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout) }); } public void Set(string key, object value, TimeSpan timeout, ExpireType expireType) { string cacheKey = BuildKey(key); if (expireType == ExpireType.Absolute) { //这里没转换标准时间,Linux时区会有问题? _cache.SetString(cacheKey, JsonHelper.SerializeObject(value), new DistributedCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout) }); } else { _cache.SetString(cacheKey, JsonHelper.SerializeObject(value), new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = timeout }); } } public async Task SetAsync(string key, object value, TimeSpan timeout, ExpireType expireType) { string cacheKey = BuildKey(key); if (expireType == ExpireType.Absolute) { //这里没转换标准时间,Linux时区会有问题? await _cache.SetStringAsync(cacheKey, JsonHelper.SerializeObject(value), new DistributedCacheEntryOptions { AbsoluteExpiration = new DateTimeOffset(DateTime.Now + timeout) }); } else { await _cache.SetStringAsync(cacheKey, JsonHelper.SerializeObject(value), new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = timeout }); } } public string Get(string idKey) { if (!string.IsNullOrEmpty(idKey)) { return _cache.GetString(BuildKey(idKey)); } else { return null; } } public async Task<string> GetAsync(string key) { if (!string.IsNullOrEmpty(key)) { return await _cache.GetStringAsync(BuildKey(key)); } else { return null; } } public T Get<T>(string key) { var cache = Get(key); if (!string.IsNullOrEmpty(cache)) { return JsonHelper.DeserializeObject<T>(cache); } else { return default(T); } } public async Task<T> GetAsync<T>(string key) { var cache = await GetAsync(key); if (!string.IsNullOrEmpty(cache)) { return JsonHelper.DeserializeObject<T>(cache); } else { return default(T); } } public void Remove(string key) { _cache.Remove(BuildKey(key)); } public async Task RemoveAsync(string key) { await _cache.RemoveAsync(BuildKey(key)); } public void Refresh(string key) { _cache.Refresh(BuildKey(key)); } public async Task RefreshAsync(string key) { await _cache.RefreshAsync(BuildKey(key)); } }
(3)CacheOptions.cs
/// <summary> /// 缓存配置信息 /// </summary> public class CacheOptions { /// <summary> /// 缓存类型 /// </summary> public CacheType CacheType { get; set; } /// <summary> /// Redis缓存配置信息 /// </summary> public RedisCache Redis { get; set; } /// <summary> /// SqlServer缓存配置信息 /// </summary> public SqlServerCache SqlServer { get; set; } /// <summary> /// NCache缓存配置信息 /// </summary> public NCache NCache { get; set; } /// <summary> /// Azure CosmosDB 缓存配置信息 /// </summary> public CosmosCache Cosmos { get; set; } } /// <summary> /// Redis缓存配置信息 /// </summary> public class RedisCache { /// <summary> /// Redis缓存节点地址 /// </summary> public string ConnectionString { get; set; } /// <summary> /// Redis实例名称 /// </summary> public string InstanceName { get; set; } } /// <summary> /// SqlServer缓存配置信息 /// </summary> public class SqlServerCache { /// <summary> /// SqlServer 数据库连接地址 /// </summary> public string ConnectionString { get; set; } /// <summary> /// /// </summary> public string SchemaName { get; set; } /// <summary> /// 表名称 /// </summary> public string TableName { get; set; } } /// <summary> /// NCache缓存配置信息 /// </summary> public class NCache { /// <summary> /// /// </summary> public string CacheName { get; set; } /// <summary> /// /// </summary> public bool EnableLogs { get; set; } /// <summary> /// /// </summary> public bool ExceptionsEnabled { get; set; } } /// <summary> /// Azure CosmosDB 缓存配置信息 /// </summary> public class CosmosCache { /// <summary> /// /// </summary> public string CacheName { get; set; } /// <summary> /// /// </summary> public bool EnableLogs { get; set; } /// <summary> /// /// </summary> public bool ExceptionsEnabled { get; set; } }
(4)CacheType.cs
public enum CacheType { /// <summary> /// 使用内存缓存(不支持分布式) /// </summary> Memory, /// <summary> /// 使用Redis缓存(支持分布式) /// </summary> Redis, /// <summary> /// 使用NCache 缓存(支持分布式) /// </summary> NCache, /// <summary> /// 使用Azure CosmosDB 缓存(支持分布式) /// </summary> Cosmos }
(5)ExpireType.cs
public enum ExpireType { /// <summary> /// 绝对过期 /// 注:即自创建一段时间后就过期 /// </summary> Absolute, /// <summary> /// 相对过期 /// 注:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长 /// </summary> Relative, }
(6)JsonHelper.cs
using System.Xml;
using System.Xml.Linq;
using Newtonsoft.Json;
public class JsonHelper { /// <summary> /// 将object转换成json字符串 /// </summary> /// <param name="value">object</param> /// <returns></returns> public static string SerializeObject(object value) { return JsonConvert.SerializeObject(value); } /// <summary> /// 将json字符串转换成object /// </summary> /// <param name="value"></param> /// <returns></returns> public static object DeserializeObject(string value) { return JsonConvert.DeserializeObject(value); } /// <summary> /// 将json字符串转换成对象 /// </summary> /// <param name="value">json字符</param> /// <returns></returns> public static T DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value); } /// <summary> /// 将XmlNode转换成json字符串 /// </summary> /// <param name="value">object</param> /// <returns></returns> public static string SerializeXmlNode(XmlNode value) { return JsonConvert.SerializeXmlNode(value); } /// <summary> /// 将XObject转换成json字符串 /// </summary> /// <param name="value">object</param> /// <returns></returns> public static string SerializeXNode(XObject value) { return JsonConvert.SerializeXNode(value); } /// <summary> /// 将json字符串转换成Xml /// </summary> /// <param name="value">json字符</param> /// <returns></returns> public static XmlDocument DeserializeXmlNode(string value) { return JsonConvert.DeserializeXmlNode(value); } /// <summary> /// 将json字符串转换成XNode /// </summary> /// <param name="value">json字符</param> /// <returns></returns> public static XDocument DeserializeXNode(string value) { return JsonConvert.DeserializeXNode(value); } }
Program文件中写入一下代码:
//获取缓存方式 var cacheOption = Configuration.GetSection("Cache").Get<CacheOptions>(); switch (cacheOption.CacheType) { case CacheType.Memory: //缓存 MemoryCache builder.Services.AddDistributedMemoryCache(); break; case CacheType.Redis: //缓存 RedisCache builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = cacheOption.Redis.ConnectionString; options.InstanceName = cacheOption.Redis.InstanceName; }); break; case CacheType.SqlServer: //缓存 SqlServerCache builder.Services.AddDistributedSqlServerCache(options => { options.ConnectionString = cacheOption.SqlServer.ConnectionString; options.SchemaName = cacheOption.SqlServer.SchemaName; options.TableName = cacheOption.SqlServer.TableName; }); break; case CacheType.NCache: //缓存 NCache builder.Services.AddNCacheDistributedCache(options => { options.CacheName = cacheOption.NCache.CacheName; options.EnableLogs = cacheOption.NCache.EnableLogs; options.ExceptionsEnabled = cacheOption.NCache.ExceptionsEnabled; }); break; case CacheType.Cosmos: //缓存 Azure CosmosDB builder.Services.AddCosmosCache((CosmosCacheOptions options) => { options.ContainerName = cacheOption.Cosmos.ContainerName; options.DatabaseName = cacheOption.Cosmos.DatabaseName; options.ClientBuilder = new CosmosClientBuilder(cacheOption.Cosmos.CosmosConnectionString); options.CreateIfNotExists = cacheOption.Cosmos.CreateIfNotExists; }); break; default: break; }
配置文件的内容:
"Cache": { "CacheType": "Memory", // "Memory OR Redis OR SqlServer OR NCache OR Cosmos" "Redis": { "ConnectionString": "127.0.0.1:6379", //Redis节点地址,定义详见 https://github.com/2881099/csredis "InstanceName": "RedisInstance" }, "SqlServer": { "ConnectionString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DistCache;Integrated Security=True;", "SchemaName": "dbo", "TableName": "TestCache" }, "NCache": { "CacheName": "", "EnableLogs": true, "ExceptionsEnabled": true }, "Cosmos": { "ContainerName": "", "DatabaseName": "", "CosmosClient": "", "CreateIfNotExists": true } }
使用实例代码:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using DoNet.Cache;
public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly ICache _cache; public HomeController(ILogger<HomeController> logger, IDistributedCache cache) { _logger = logger; _cache = new CacheHelper(cache); } public IActionResult Index() { string key = "aa"; string cache_value = "hello cache"; //同步方法 _cache.Set(key, cache_value); string v = _cache.Get<string>(key); _cache.Remove(key); return View(); } }
运行代码可以跑通。