首页 > 其他分享 >.NET8 缓存的使用

.NET8 缓存的使用

时间:2024-08-12 17:38:48浏览次数:13  
标签:缓存 string NET8 value cache key 使用 public

.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
    }
View Code

(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));
        }

    }
View Code

(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; }
    }
View Code

(4)CacheType.cs

    public enum CacheType
    {
        /// <summary>
        /// 使用内存缓存(不支持分布式)
        /// </summary>
        Memory,

        /// <summary>
        /// 使用Redis缓存(支持分布式)
        /// </summary>
        Redis,

        /// <summary>
        /// 使用NCache 缓存(支持分布式)
        /// </summary>
        NCache,

        /// <summary>
        /// 使用Azure CosmosDB 缓存(支持分布式)
        /// </summary>
        Cosmos
    }
View Code

(5)ExpireType.cs

    public enum ExpireType
    {
        /// <summary>
        /// 绝对过期
        /// 注:即自创建一段时间后就过期
        /// </summary>
        Absolute,

        /// <summary>
        /// 相对过期
        /// 注:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长
        /// </summary>
        Relative,
    }
View Code

(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);
        }
    }
View Code

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;

    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        readonly IDistributedCache _cache;

        public HomeController(ILogger<HomeController> logger, IDistributedCache cache)
        {
            _logger = logger;
            _cache = cache;
        }

        public IActionResult Index()
        {
            CacheHelper cacheHelper = new CacheHelper(_cache);
            
            string key = "aa";
            string cache_value = "hello cache";
            //同步方法
            cacheHelper.Set(key, cache_value);
            string v = cacheHelper.Get<string>(key);
            cacheHelper.Remove(key);

            return View();
        }
    }

运行代码可以跑通。

标签:缓存,string,NET8,value,cache,key,使用,public
From: https://www.cnblogs.com/wsk198726/p/18355443

相关文章

  • java .stream(). 使用介绍 Streams API
    Java8引入了StreamsAPI,它允许我们以声明性方式处理序列的数据。.stream()是这一API的核心方法,用于从一个数据源(如数组、集合等)创建一个流(Stream)。以下是.stream()方法的一些基本使用介绍:1.从集合创建流List<String>myList=Arrays.asList("a","b","c");Stream<S......
  • BOOST c++库学习 之 boost.thread入门实战指南 使用boost.thread库以及读写锁mutex的
    Boost.Thread库简介1.概述Boost.Thread库是Boost库中专门用于处理多线程编程的模块。它提供了一组跨平台的线程管理和同步工具,帮助开发者在C++中更轻松地编写多线程程序。Boost.Thread的设计目标是使多线程编程更加简单、可靠,同时保持高效和可移植性。2.Boost.Thread......
  • 爬虫如何使用HTTPS代理,让数据抓取更稳更快
    在网络爬虫的世界里,使用HTTPS代理就像是给你的爬虫装上了“隐形斗篷”,不仅能提高抓取效率,还能保护你的隐私。今天,我们来聊聊如何在爬虫中使用HTTPS代理,让你的数据抓取更稳更快。为什么要使用HTTPS代理?在进行数据抓取时,使用HTTPS代理有几个显著的好处:提高抓取效率:通过使用......
  • 使用orcale数据库的springboot项目打war包部署到tomcat后启动报错解决办法(缺少UCP数据
    我将在我本丢运行ok的springboot项目打成war包后部署到tomcat后,启动tomcat的时候一直显示:由于之前的错误,Context[/ruoyi]启动失败......,查看tomcat的日志文件发现报错:12-Aug-202410:20:35.183严重[main]org.apache.catalina.core.StandardContext.listenerStart配置应用......
  • api代理爬虫:了解其基本原理和使用方法
    ​API代理爬虫的使用指南在数据驱动的时代,API(应用程序接口)成为了获取数据的重要途径。而通过API代理爬虫,我们可以高效地采集和处理数据,尤其是在面对反爬虫机制时。本文将为你介绍API代理爬虫的基本概念、工作原理以及如何使用。1.什么是API代理爬虫?API代理爬虫是一种结合了......
  • dev c++的使用
    前置软件:devc++首先开始学习前,先把软件下好点开devc++,发现有一个页面如下图:这时按Ctrl+n即可打开一个页面如下:这时你是否已经跃跃欲试了吗,哦不,还得慢慢来先敲上一段代码#include<iostream>usingnamespacestd;intmain(){return0;}好了可以了就完了可以......
  • __int128的使用
    dzk在做蛋糕上的草莓是蛋糕的灵魂这道题的时候写的\(longlong\)爆了,补题的时候经lwq指点,学习了__int128的用法int最大值\(2^{32-1}-1\)longlong最大值\(2^{64-1}-1\)__int128最大值\(2^{64-1}-1\)关于__int128:只能进行四则运算,不能用cin和cout来输出,不能用位运算来......
  • AI绘画实操 Stable Diffusion 到底怎么玩儿,新手必看的AI绘画入门安装使用教程
    大家好,我是灵魂画师向阳2024年,是AI绘画技术飞速发展的一年,各种AI绘画工具层出不穷,为了让大家在了解和学习AI绘画的过程中少走弯路,今天我将详细介绍目前世界上使用用户最多,社区最大,生态最丰富的免费图像生成模型——StableDiffusion,并为你提供详细的安装教程,让你轻松踏入AI......
  • 【ComfyUI】AI绘画 一键换人 脸工作流,学会你也可以实现随时换脸啦~低调使用,别太邪恶哦!
    大家好,我是画画的小强在这个数字时代,变脸不再是魔术师的专利,也不是好莱坞特效的专属领域。现在,有了【comfyui】AI绘画一键换脸工作流,你也能轻松掌握这项令人惊叹的技术!只需动动手指,瞬间就能换上一张新的面孔,仿佛打开了通往平行世界的大门。无论是想在社交媒体上尝试新形象,......
  • 百度地图的使用
    百度地图作为一个开源平台在使用的时候具备诸多的功能在介绍之前先分享官网百度地图-百万开发者首选的地图服务商,提供专属的行业解决方案百度地图开放平台作为百万开发者首选的地图服务商,不仅面向开发者提供包括API、SDK、SaaS、PaaS、DaaS等服务,还面向B/G两端提供专业的行......