首页 > 其他分享 >net8 设置缓存

net8 设置缓存

时间:2024-01-15 12:12:54浏览次数:27  
标签:缓存 string res cache Task cacheKey 设置 net8 public

1、项目用到依赖注入参考:

https://www.cnblogs.com/handsomeziff/p/16390502.html

2、新建ICaching接口

using Microsoft.Extensions.Caching.Distributed;

namespace YYApi.Caches
{
    /// <summary>
    /// 缓存抽象接口,基于IDistributedCache封装
    /// </summary>
    public interface ICaching
    {
        public IDistributedCache Cache { get; }
        void AddCacheKey(string cacheKey);
        Task AddCacheKeyAsync(string cacheKey);

        void DelByPattern(string key);
        Task DelByPatternAsync(string key);

        void DelCacheKey(string cacheKey);
        Task DelCacheKeyAsync(string cacheKey);

        bool Exists(string cacheKey);
        Task<bool> ExistsAsync(string cacheKey);

        List<string> GetAllCacheKeys();
        Task<List<string>> GetAllCacheKeysAsync();

        T Get<T>(string cacheKey);
        Task<T> GetAsync<T>(string cacheKey);

        object Get(Type type, string cacheKey);
        Task<object> GetAsync(Type type, string cacheKey);

        string GetString(string cacheKey);
        Task<string> GetStringAsync(string cacheKey);

        void Remove(string key);
        Task RemoveAsync(string key);

        void RemoveAll();
        Task RemoveAllAsync();

        void Set<T>(string cacheKey, T value, TimeSpan? expire = null);
        Task SetAsync<T>(string cacheKey, T value);
        Task SetAsync<T>(string cacheKey, T value, TimeSpan expire);

        void SetPermanent<T>(string cacheKey, T value);
        Task SetPermanentAsync<T>(string cacheKey, T value);

        void SetString(string cacheKey, string value, TimeSpan? expire = null);
        Task SetStringAsync(string cacheKey, string value);
        Task SetStringAsync(string cacheKey, string value, TimeSpan expire);

        Task DelByParentKeyAsync(string key);
    }
}
View Code

3、新建Caching类

using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System.Text;
using YYApi.Const;

namespace YYApi.Caches
{
    public class Caching : ICaching
    {
        private readonly IDistributedCache _cache;

        public Caching(IDistributedCache cache)
        {
            _cache = cache;
        }

        private byte[] GetBytes<T>(T source)
        {
            return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(source));
        }

        public IDistributedCache Cache => _cache;

        public void AddCacheKey(string cacheKey)
        {
            var res = _cache.GetString(CacheConst.KeyAll);
            var allkeys = string.IsNullOrWhiteSpace(res) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(res);
            if (!allkeys.Any(m => m == cacheKey))
            {
                allkeys.Add(cacheKey);
                _cache.SetString(CacheConst.KeyAll, JsonConvert.SerializeObject(allkeys));
            }
        }

        /// <summary>
        /// 增加缓存Key
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public async Task AddCacheKeyAsync(string cacheKey)
        {
            var res = await _cache.GetStringAsync(CacheConst.KeyAll);
            var allkeys = string.IsNullOrWhiteSpace(res) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(res);
            if (!allkeys.Any(m => m == cacheKey))
            {
                allkeys.Add(cacheKey);
                await _cache.SetStringAsync(CacheConst.KeyAll, JsonConvert.SerializeObject(allkeys));
            }
        }

        public void DelByPattern(string key)
        {
            var allkeys = GetAllCacheKeys();
            if (allkeys == null) return;

            var delAllkeys = allkeys.Where(u => u.Contains(key)).ToList();
            delAllkeys.ForEach(u => { _cache.Remove(u); });

            // 更新所有缓存键
            allkeys = allkeys.Where(u => !u.Contains(key)).ToList();
            _cache.SetString(CacheConst.KeyAll, JsonConvert.SerializeObject(allkeys));
        }

        /// <summary>
        /// 删除某特征关键字缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task DelByPatternAsync(string key)
        {
            var allkeys = await GetAllCacheKeysAsync();
            if (allkeys == null) return;

            var delAllkeys = allkeys.Where(u => u.Contains(key)).ToList();
            delAllkeys.ForEach(u => { _cache.Remove(u); });

            // 更新所有缓存键
            allkeys = allkeys.Where(u => !u.Contains(key)).ToList();
            await _cache.SetStringAsync(CacheConst.KeyAll, JsonConvert.SerializeObject(allkeys));
        }

        public void DelCacheKey(string cacheKey)
        {
            var res = _cache.GetString(CacheConst.KeyAll);
            var allkeys = string.IsNullOrWhiteSpace(res) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(res);
            if (allkeys.Any(m => m == cacheKey))
            {
                allkeys.Remove(cacheKey);
                _cache.SetString(CacheConst.KeyAll, JsonConvert.SerializeObject(allkeys));
            }
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public async Task DelCacheKeyAsync(string cacheKey)
        {
            var res = await _cache.GetStringAsync(CacheConst.KeyAll);
            var allkeys = string.IsNullOrWhiteSpace(res) ? new List<string>() : JsonConvert.DeserializeObject<List<string>>(res);
            if (allkeys.Any(m => m == cacheKey))
            {
                allkeys.Remove(cacheKey);
                await _cache.SetStringAsync(CacheConst.KeyAll, JsonConvert.SerializeObject(allkeys));
            }
        }

        public bool Exists(string cacheKey)
        {
            var res = _cache.Get(cacheKey);
            return res != null;
        }

        /// <summary>
        /// 检查给定 key 是否存在
        /// </summary>
        /// <param name="cacheKey">键</param>
        /// <returns></returns>
        public async Task<bool> ExistsAsync(string cacheKey)
        {
            var res = await _cache.GetAsync(cacheKey);
            return res != null;
        }

        public List<string> GetAllCacheKeys()
        {
            var res = _cache.GetString(CacheConst.KeyAll);
            return string.IsNullOrWhiteSpace(res) ? null : JsonConvert.DeserializeObject<List<string>>(res);
        }

        /// <summary>
        /// 获取所有缓存列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<string>> GetAllCacheKeysAsync()
        {
            var res = await _cache.GetStringAsync(CacheConst.KeyAll);
            return string.IsNullOrWhiteSpace(res) ? null : JsonConvert.DeserializeObject<List<string>>(res);
        }

        public T Get<T>(string cacheKey)
        {
            var res = _cache.Get(cacheKey);
            return res == null ? default : JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(res));
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public async Task<T> GetAsync<T>(string cacheKey)
        {
            var res = await _cache.GetAsync(cacheKey);
            return res == null ? default : JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(res));
        }

        public object Get(Type type, string cacheKey)
        {
            var res = _cache.Get(cacheKey);
            return res == null ? default : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(res), type);
        }

        public async Task<object> GetAsync(Type type, string cacheKey)
        {
            var res = await _cache.GetAsync(cacheKey);
            return res == null ? default : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(res), type);
        }

        public string GetString(string cacheKey)
        {
            return _cache.GetString(cacheKey);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public async Task<string> GetStringAsync(string cacheKey)
        {
            return await _cache.GetStringAsync(cacheKey);
        }

        public void Remove(string key)
        {
            _cache.Remove(key);
            DelCacheKey(key);
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task RemoveAsync(string key)
        {
            await _cache.RemoveAsync(key);
            await DelCacheKeyAsync(key);
        }

        public void RemoveAll()
        {
            var catches = GetAllCacheKeys();
            foreach (var @catch in catches) Remove(@catch);

            catches.Clear();
            _cache.SetString(CacheConst.KeyAll, JsonConvert.SerializeObject(catches));
        }

        public async Task RemoveAllAsync()
        {
            var catches = await GetAllCacheKeysAsync();
            foreach (var @catch in catches) await RemoveAsync(@catch);

            catches.Clear();
            await _cache.SetStringAsync(CacheConst.KeyAll, JsonConvert.SerializeObject(catches));
        }


        public void Set<T>(string cacheKey, T value, TimeSpan? expire = null)
        {
            _cache.Set(cacheKey, GetBytes(value),
                expire == null
                    ? new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6) }
                    : new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = expire });

            AddCacheKey(cacheKey);
        }

        /// <summary>
        /// 增加对象缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task SetAsync<T>(string cacheKey, T value)
        {
            await _cache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)),
                new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6) });

            await AddCacheKeyAsync(cacheKey);
        }

        /// <summary>
        /// 增加对象缓存,并设置过期时间
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="value"></param>
        /// <param name="expire"></param>
        /// <returns></returns>
        public async Task SetAsync<T>(string cacheKey, T value, TimeSpan expire)
        {
            await _cache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)),
                new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = expire });

            await AddCacheKeyAsync(cacheKey);
        }

        public void SetPermanent<T>(string cacheKey, T value)
        {
            _cache.Set(cacheKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)));
            AddCacheKey(cacheKey);
        }

        public async Task SetPermanentAsync<T>(string cacheKey, T value)
        {
            await _cache.SetAsync(cacheKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)));
            await AddCacheKeyAsync(cacheKey);
        }

        public void SetString(string cacheKey, string value, TimeSpan? expire = null)
        {
            if (expire == null)
                _cache.SetString(cacheKey, value, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6) });
            else
                _cache.SetString(cacheKey, value, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = expire });

            AddCacheKey(cacheKey);
        }

        /// <summary>
        /// 增加字符串缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public async Task SetStringAsync(string cacheKey, string value)
        {
            await _cache.SetStringAsync(cacheKey, value, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6) });

            await AddCacheKeyAsync(cacheKey);
        }

        /// <summary>
        /// 增加字符串缓存,并设置过期时间
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="value"></param>
        /// <param name="expire"></param>
        /// <returns></returns>
        public async Task SetStringAsync(string cacheKey, string value, TimeSpan expire)
        {
            await _cache.SetStringAsync(cacheKey, value, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = expire });

            await AddCacheKeyAsync(cacheKey);
        }


        /// <summary>
        /// 缓存最大角色数据范围
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="dataScopeType"></param>
        /// <returns></returns>
        public async Task SetMaxDataScopeType(long userId, int dataScopeType)
        {
            var cacheKey = CacheConst.KeyMaxDataScopeType + userId;
            await SetStringAsync(cacheKey, dataScopeType.ToString());

            await AddCacheKeyAsync(cacheKey);
        }

        /// <summary>
        ///  根据父键清空
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task DelByParentKeyAsync(string key)
        {
            var allkeys = await GetAllCacheKeysAsync();
            if (allkeys == null) return;

            var delAllkeys = allkeys.Where(u => u.StartsWith(key)).ToList();
            delAllkeys.ForEach(Remove);
            // 更新所有缓存键
            allkeys = allkeys.Where(u => !u.StartsWith(key)).ToList();
            await SetStringAsync(CacheConst.KeyAll, JsonConvert.SerializeObject(allkeys));
        }
    }
}
View Code

4、新建缓存相关类CacheConst

namespace YYApi.Const
{
    /// <summary>
    /// 缓存相关常量
    /// </summary>
    public class CacheConst
    {
        /// <summary>
        /// 用户缓存
        /// </summary>
        public const string KeyUser = "user:";

        /// <summary>
        /// 用户部门缓存
        /// </summary>
        public const string KeyUserDepart = "userDepart:";

        /// <summary>
        /// 菜单缓存
        /// </summary>
        public const string KeyMenu = "menu:";

        /// <summary>
        /// 菜单
        /// </summary>
        public const string KeyPermissions = "permissions";

        /// <summary>
        /// 权限缓存
        /// </summary>
        public const string KeyPermission = "permission:";

        /// <summary>
        /// 接口路由
        /// </summary>
        public const string KeyModules = "modules";

        /// <summary>
        /// 系统配置
        /// </summary>
        public const string KeySystemConfig = "sysConfig";

        /// <summary>
        /// 查询过滤器缓存
        /// </summary>
        public const string KeyQueryFilter = "queryFilter:";

        /// <summary>
        /// 机构Id集合缓存
        /// </summary>
        public const string KeyOrgIdList = "org:";

        /// <summary>
        /// 最大角色数据范围缓存
        /// </summary>
        public const string KeyMaxDataScopeType = "maxDataScopeType:";

        /// <summary>
        /// 验证码缓存
        /// </summary>
        public const string KeyVerCode = "verCode:";

        /// <summary>
        /// 所有缓存关键字集合
        /// </summary>
        public const string KeyAll = "keys";

        /// <summary>
        /// 定时任务缓存
        /// </summary>
        public const string KeyTimer = "timer:";

        /// <summary>
        /// 在线用户缓存
        /// </summary>
        public const string KeyOnlineUser = "onlineuser:";

        /// <summary>
        /// 常量下拉框
        /// </summary>
        public const string KeyConstSelector = "selector:";

        /// <summary>
        /// swagger登录缓存
        /// </summary>
        public const string SwaggerLogin = "swaggerLogin:";
    }
}
View Code

 

5、新增缓存注册类CacheSetup.cs

using YYApi.Caches;

namespace YYApi.ServiceExtensions
{
    public static class CacheSetup
    {
        /// <summary>
        /// 统一注册缓存
        /// </summary>
        /// <param name="services"></param>
        public static void AddCacheSetup(this IServiceCollection services)
        {
            //使用内存
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();

            services.AddSingleton<ICaching, Caching>();
        }
    }
}
View Code

6、在Program.cs文件增加:

builder.Services.AddCacheSetup();

7、在Autofac增加

public class AutofacModuleRegister : Autofac.Module
{
        builder.RegisterType<Caching>().As<ICaching>().SingleInstance();
    }
}

8、使用:

新建一个控制器WeatherForecastController.cs。这里使用创建项目自助生成的控制器

using Microsoft.AspNetCore.Mvc;
using System;
using YYApi.Caches;
using YYApi.Model.YY;

namespace YYApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly ICaching _caching;
        public WeatherForecastController(ILogger<WeatherForecastController> logger, ICaching caching)
        {
            _logger = logger;
            _caching = caching;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public async Task<WeatherForecast> Get()
        {
            string cacheKey = "keyname";
            WeatherForecast model = new WeatherForecast();

            model = await _caching.GetAsync<WeatherForecast>(cacheKey);
            if (null != model)
            {
                return model;
            }
            model = new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(1)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            };
            await _caching.SetAsync(cacheKey, model, TimeSpan.FromMinutes(3));
            return model;
        }
    }
}

 

标签:缓存,string,res,cache,Task,cacheKey,设置,net8,public
From: https://www.cnblogs.com/handsomeziff/p/17965099

相关文章

  • 关于k8s关闭swap分区与swappiness设置的问题
    1、基于其出发点,k8s希望将资源限制在一个严格,精确可控范围内:Kubernetes云原生的实现目的是将运行实例紧密包装到尽可能接近100%:所有的部署、运行环境应该与CPU以及内存限定在一个可控的空间内。所以如果调度程序发送一个Pod到某一台节点机器,它不应该使用Swap。如果使用sw......
  • Redis 做缓存常见的几个问题总结
     1.数据一致性我们知道,Redis主要是用来做缓存使用,只要使用到缓存,无论是本地内存做缓存还是使用Redis做缓存,那么就会存在数据同步的问题。一般情况下,我们都是先读缓存数据,缓存数据有,则立即返回结果;如果没有数据,则从数据库读数据,并且把读到的数据同步到缓存里,提供下次读请......
  • 面试官:如何保证本地缓存的一致性?
    有人可能看到“本地缓存”这四个字就会觉得不屑,“哼,现在谁还用本地缓存?直接用分布式缓存不就完了嘛”。然而,这就像你有一辆超级豪华的房车一样,虽然它空间很大,设备很全,但你去市中心的时候,依然会开小轿车一样,为啥?好停车啊!所以,不同的缓存类型是有不同得使用场景的。并且,为了防止缓......
  • Mysql中设置只允许指定ip能连接访问(可视化工具的方式)
    场景Mysql中怎样设置指定ip远程访问连接:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/115308120前面设置root账户指定ip能连接访问是通过命令行的方式,如果通过可视化工具比如Navicat来实现。注:博客:https://blog.csdn.net/badao_liumang_qizhi实现1、使用N......
  • PostgreSQL 数据库安全之检验数据块的损坏- data_checksums 参数设置
    默认情况下,数据页不受校验和保护,但可以选择为集群启用这一功能。启用后,每个数据页都包含一个校验和,该校验和在写入该页时更新,并在每次读取该页时进行验证。只有数据页受校验和保护;内部数据结构和临时文件不是。校验和通常在使用initdb初始化集群时启用。还可以在以后的脱......
  • PostgreSQL 数据库日志收集功能开启一什么时候写-参数 log_min_messages 等其他参数设
    log_min_messages(enum)控制将哪些消息级别写入服务器日志。可以取值为:DEBUG5、DEBUG4、DEBUG3、DEBUG2、DEBUG1、INFO、NOTICE、WARNING、ERROR、LOG、FATAL、PANIC。每个关卡都包含了它之后的所有关卡。级别越高,发送到日志的消息就越少。默认值是WARNING。注意,这里的LOG......
  • PostgreSQL 数据库日志收集功能开启-参数 log_truncate_on_rotation 设置
    log_truncate_on_rotation(boolean)--默认为off,设置为on的话,文件内容覆盖方式:off后面附加,on:清空再加当启用logging_collector时,此参数将导致PostgreSQL截断(覆盖)而不是追加到任何同名的现有日志文件。但是,截断只会在由于基于时间的旋转而打开新文件时发生,而不会在服务......
  • PostgreSQL 数据库日志收集功能开启-参数 syslog_ident 等其他参数设置
    syslog_ident(string)当日志记录到syslog日志时,该参数决定了用于识别syslog日志中PostgreSQL消息的程序名称。默认为postgres。该参数只能在postgresql.conf文件或服务器命令行中设置。syslog_sequence_numbers(boolean)当日志记录到syslog并且开启此选项时(默认设置......
  • npm仓库设置
    1.默认仓库,是国外的,安装会很慢D:\workspace\vue-test>npmconfiggetregistryhttps://registry.npmjs.org/2.设置npm仓库D:\workspace\vue-test>npmconfigsetregistryhttps://registry.apm.taobao.orgD:\workspace\vue-test>npmconfiggetregistryhttps:/......
  • PostgreSQL 数据库日志收集功能开启-参数 log_file_mode 设置
    log_file_mode(integer)日志文件权限,默认为0600在Unix系统上,当启用logging_collector时,此参数设置日志文件的权限。(在MicrosoftWindows上,此参数被忽略。)参数值应该是一个数字模式,以chmod和umask系统调用接受的格式指定。(要使用习惯的八进制格式,数字必须以0(零)开头......