From 1fbe4fc978e31c35dd2f793331c5a9fa1faf84c7 Mon Sep 17 00:00:00 2001 From: "jonah.fu" Date: Thu, 14 Aug 2025 13:15:50 +0800 Subject: [PATCH] =?UTF-8?q?feat(caching):=20=E5=AE=9E=E7=8E=B0=E5=88=86?= =?UTF-8?q?=E5=B8=83=E5=BC=8F=E7=BC=93=E5=AD=98=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 CacheService 和 ICacheService 接口,提供缓存操作功能 - 在 Startup.cs 中配置缓存服务- 更新 appsettings.json,增加 RedisCache 和 CacheSettings 配置- 修改 XCode.config,调整缓存相关设置 --- COMCMS.Web/Models/CacheSettings.cs | 131 +++++++++++++++++++++++++++ COMCMS.Web/Services/CacheService.cs | 90 ++++++++++++++++++ COMCMS.Web/Services/ICacheService.cs | 80 ++++++++++++++++ COMCMS.Web/Startup.cs | 11 ++- COMCMS.Web/appsettings.json | 21 ++++- XCoder/Config/XCode.config | 16 ++-- 6 files changed, 339 insertions(+), 10 deletions(-) create mode 100644 COMCMS.Web/Models/CacheSettings.cs create mode 100644 COMCMS.Web/Services/CacheService.cs create mode 100644 COMCMS.Web/Services/ICacheService.cs diff --git a/COMCMS.Web/Models/CacheSettings.cs b/COMCMS.Web/Models/CacheSettings.cs new file mode 100644 index 0000000..947838b --- /dev/null +++ b/COMCMS.Web/Models/CacheSettings.cs @@ -0,0 +1,131 @@ +using System; + +namespace COMCMS.Web.Models +{ + /// + /// 缓存配置设置 + /// + public class CacheSettings + { + /// + /// 默认过期时间(分钟) + /// + public int DefaultExpirationMinutes { get; set; } = 30; + + /// + /// 系统配置缓存过期时间(分钟) + /// + public int SystemConfigExpirationMinutes { get; set; } = 60; + + /// + /// 文章缓存过期时间(分钟) + /// + public int ArticleExpirationMinutes { get; set; } = 20; + + /// + /// 产品缓存过期时间(分钟) + /// + public int ProductExpirationMinutes { get; set; } = 20; + + /// + /// 分类缓存过期时间(分钟) + /// + public int CategoryExpirationMinutes { get; set; } = 120; + + /// + /// 用户缓存过期时间(分钟) + /// + public int UserExpirationMinutes { get; set; } = 15; + + /// + /// 订单缓存过期时间(分钟) + /// + public int OrderExpirationMinutes { get; set; } = 10; + + /// + /// 是否启用响应缓存 + /// + public bool EnableResponseCaching { get; set; } = true; + + /// + /// 是否启用分布式缓存 + /// + public bool EnableDistributedCaching { get; set; } = true; + + /// + /// 获取默认过期时间跨度 + /// + public TimeSpan DefaultExpiration => TimeSpan.FromMinutes(DefaultExpirationMinutes); + + /// + /// 获取系统配置过期时间跨度 + /// + public TimeSpan SystemConfigExpiration => TimeSpan.FromMinutes(SystemConfigExpirationMinutes); + + /// + /// 获取文章过期时间跨度 + /// + public TimeSpan ArticleExpiration => TimeSpan.FromMinutes(ArticleExpirationMinutes); + + /// + /// 获取产品过期时间跨度 + /// + public TimeSpan ProductExpiration => TimeSpan.FromMinutes(ProductExpirationMinutes); + + /// + /// 获取分类过期时间跨度 + /// + public TimeSpan CategoryExpiration => TimeSpan.FromMinutes(CategoryExpirationMinutes); + + /// + /// 获取用户过期时间跨度 + /// + public TimeSpan UserExpiration => TimeSpan.FromMinutes(UserExpirationMinutes); + + /// + /// 获取订单过期时间跨度 + /// + public TimeSpan OrderExpiration => TimeSpan.FromMinutes(OrderExpirationMinutes); + } + + /// + /// Redis缓存配置 + /// + public class RedisCacheSettings + { + /// + /// 连接字符串 + /// + public string ConnectionString { get; set; } = "server=127.0.0.1;password=;db=2"; + + /// + /// 实例名称 + /// + public string InstanceName { get; set; } = "COMCMS:"; + + /// + /// 默认数据库 + /// + public int DefaultDatabase { get; set; } = 2; + + /// + /// 连接超时时间(毫秒) + /// + public int ConnectTimeout { get; set; } = 5000; + + /// + /// 同步超时时间(毫秒) + /// + public int SyncTimeout { get; set; } = 5000; + + /// + /// 是否中断连接 + /// + public bool AbortConnect { get; set; } = false; + + /// + /// 连接重试次数 + /// + public int ConnectRetry { get; set; } = 3; + } +} diff --git a/COMCMS.Web/Services/CacheService.cs b/COMCMS.Web/Services/CacheService.cs new file mode 100644 index 0000000..c9e8a95 --- /dev/null +++ b/COMCMS.Web/Services/CacheService.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using COMCMS.Common; +using COMCMS.Web.Models; +using Microsoft.Extensions.Options; +using NewLife.Caching; +using NewLife.Caching.Services; + +namespace COMCMS.Web.Services +{ + public class CacheService : ICacheService + { + private readonly NewLife.Caching.ICacheProvider _cacheProvider; + private readonly CacheSettings _settings; + private readonly string _prefix; + + public CacheService(NewLife.Caching.ICacheProvider cacheProvider, IOptions settings) + { + _cacheProvider = cacheProvider; + _settings = settings.Value; + _prefix = Utils.PrefixKey ?? "comcms:"; + } + + private string BuildKey(string key) => string.Concat(_prefix, key ?? string.Empty); + + public async Task GetAsync(string key) + { + return await Task.FromResult(_cacheProvider.Cache.Get(BuildKey(key))); + } + + public async Task SetAsync(string key, T value, TimeSpan? expiration = null) + { + var expireSeconds = (int)(expiration ?? _settings.DefaultExpiration).TotalSeconds; + _cacheProvider.Cache.Add(BuildKey(key), value, expireSeconds); + await Task.CompletedTask; + } + + public async Task RemoveAsync(string key) + { + _cacheProvider.Cache.Remove(BuildKey(key)); + await Task.CompletedTask; + } + + public async Task RemoveByPatternAsync(string pattern) + { + // 暂不支持模式删除,保留占位实现 + await Task.CompletedTask; + } + + public async Task ExistsAsync(string key) + { + var val = _cacheProvider.Cache.Get(BuildKey(key)); + return await Task.FromResult(val != null); + } + + public async Task GetOrSetAsync(string key, Func> factory, TimeSpan? expiration = null) + { + var cacheKey = BuildKey(key); + var existed = _cacheProvider.Cache.Get(cacheKey); + if (!EqualityComparer.Default.Equals(existed, default)) return existed; + + var data = await factory(); + await SetAsync(key, data, expiration); + return data; + } + + public async Task RefreshAsync(string key, TimeSpan expiration) + { + var cacheKey = BuildKey(key); + var val = _cacheProvider.Cache.Get(cacheKey); + if (val != null) _cacheProvider.Cache.Add(cacheKey, val, (int)expiration.TotalSeconds); + await Task.CompletedTask; + } + + public async Task GetCacheSizeAsync() + { + // 暂无法获取容量,返回0 + return await Task.FromResult(0L); + } + + public async Task ClearAllAsync() + { + // 暂不提供全清功能 + await Task.CompletedTask; + } + } +} diff --git a/COMCMS.Web/Services/ICacheService.cs b/COMCMS.Web/Services/ICacheService.cs new file mode 100644 index 0000000..19caec8 --- /dev/null +++ b/COMCMS.Web/Services/ICacheService.cs @@ -0,0 +1,80 @@ +using System; +using System.Threading.Tasks; + +namespace COMCMS.Web.Services +{ + /// + /// 缓存服务接口 + /// + public interface ICacheService + { + /// + /// 获取缓存值 + /// + /// 数据类型 + /// 缓存键 + /// 缓存值 + Task GetAsync(string key); + + /// + /// 设置缓存值 + /// + /// 数据类型 + /// 缓存键 + /// 缓存值 + /// 过期时间 + /// + Task SetAsync(string key, T value, TimeSpan? expiration = null); + + /// + /// 移除缓存 + /// + /// 缓存键 + /// + Task RemoveAsync(string key); + + /// + /// 根据模式移除缓存 + /// + /// 模式 + /// + Task RemoveByPatternAsync(string pattern); + + /// + /// 检查缓存是否存在 + /// + /// 缓存键 + /// + Task ExistsAsync(string key); + + /// + /// 获取或设置缓存 + /// + /// 数据类型 + /// 缓存键 + /// 数据工厂方法 + /// 过期时间 + /// + Task GetOrSetAsync(string key, Func> factory, TimeSpan? expiration = null); + + /// + /// 刷新缓存过期时间 + /// + /// 缓存键 + /// 过期时间 + /// + Task RefreshAsync(string key, TimeSpan expiration); + + /// + /// 获取缓存大小 + /// + /// + Task GetCacheSizeAsync(); + + /// + /// 清空所有缓存 + /// + /// + Task ClearAllAsync(); + } +} diff --git a/COMCMS.Web/Startup.cs b/COMCMS.Web/Startup.cs index edbfd09..c7fd34b 100644 --- a/COMCMS.Web/Startup.cs +++ b/COMCMS.Web/Startup.cs @@ -9,6 +9,7 @@ using COMCMS.Common; using COMCMS.Web.Common; using COMCMS.Web.ExceptionHandler; using COMCMS.Web.Models; +using COMCMS.Web.Services; using Lib.Core.MiddlewareExtension.Extension; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -67,7 +68,13 @@ namespace COMCMS.Web options.Cookie.HttpOnly = true; }); + // 绑定缓存设置 + services.Configure(Configuration.GetSection("CacheSettings")); + // 响应缓存 + services.AddResponseCaching(); services.AddSingleton(); + // 缓存服务封装 + services.AddSingleton(); //部分系统配置 services.Configure(Configuration.GetSection("SystemSetting")); @@ -137,7 +144,7 @@ namespace COMCMS.Web context.Response.Headers.Append("X-Frame-Options", "SAMEORIGIN"); await next(); }); - + if (env.IsDevelopment()) { @@ -161,6 +168,8 @@ namespace COMCMS.Web app.UseStaticHttpContext(); app.UseRouting(); + // 启用响应缓存 + app.UseResponseCaching(); app.UseAuthentication(); app.UseAuthorization(); diff --git a/COMCMS.Web/appsettings.json b/COMCMS.Web/appsettings.json index 31acf14..1eee950 100644 --- a/COMCMS.Web/appsettings.json +++ b/COMCMS.Web/appsettings.json @@ -5,7 +5,26 @@ "Default": "Warning" } }, - "RedisCache": "server=127.0.0.1;password=;db=2", + "RedisCache": { + "ConnectionString": "server=127.0.0.1;password=;db=2", + "InstanceName": "COMCMS:", + "DefaultDatabase": 2, + "ConnectTimeout": 5000, + "SyncTimeout": 5000, + "AbortConnect": false, + "ConnectRetry": 3 + }, + "CacheSettings": { + "DefaultExpirationMinutes": 30, + "SystemConfigExpirationMinutes": 60, + "ArticleExpirationMinutes": 20, + "ProductExpirationMinutes": 20, + "CategoryExpirationMinutes": 120, + "UserExpirationMinutes": 15, + "OrderExpirationMinutes": 10, + "EnableResponseCaching": true, + "EnableDistributedCaching": true + }, "SystemSetting": { "FileAllowedExtensions": "zip,rar,7z,doc,docx,xls,xlsx,ppt,pptx,csv,pdf,txt,gz,gzip,gif,png,jpg,jpeg,bmp,avi,fla,flv,swf,mp4,mp3,mov,mid,mpg,mpeg,rm,rmvb,wma,wav,wmv", "ImageAllowedExtensions": "gif,png,jpg,jpeg,bmp", diff --git a/XCoder/Config/XCode.config b/XCoder/Config/XCode.config index 149162e..a94331b 100644 --- a/XCoder/Config/XCode.config +++ b/XCoder/Config/XCode.config @@ -7,23 +7,23 @@ - 1000 + 2000 4096 - false + true - 0 + 30 - 0 + 3 - 0 + 300 - 10 + 600 - 10 + 600 - 10 + 300 On