feat(caching): 实现分布式缓存服务
- 新增 CacheService 和 ICacheService 接口,提供缓存操作功能 - 在 Startup.cs 中配置缓存服务- 更新 appsettings.json,增加 RedisCache 和 CacheSettings 配置- 修改 XCode.config,调整缓存相关设置
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
using System;
|
||||
|
||||
namespace COMCMS.Web.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// 缓存配置设置
|
||||
/// </summary>
|
||||
public class CacheSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// 默认过期时间(分钟)
|
||||
/// </summary>
|
||||
public int DefaultExpirationMinutes { get; set; } = 30;
|
||||
|
||||
/// <summary>
|
||||
/// 系统配置缓存过期时间(分钟)
|
||||
/// </summary>
|
||||
public int SystemConfigExpirationMinutes { get; set; } = 60;
|
||||
|
||||
/// <summary>
|
||||
/// 文章缓存过期时间(分钟)
|
||||
/// </summary>
|
||||
public int ArticleExpirationMinutes { get; set; } = 20;
|
||||
|
||||
/// <summary>
|
||||
/// 产品缓存过期时间(分钟)
|
||||
/// </summary>
|
||||
public int ProductExpirationMinutes { get; set; } = 20;
|
||||
|
||||
/// <summary>
|
||||
/// 分类缓存过期时间(分钟)
|
||||
/// </summary>
|
||||
public int CategoryExpirationMinutes { get; set; } = 120;
|
||||
|
||||
/// <summary>
|
||||
/// 用户缓存过期时间(分钟)
|
||||
/// </summary>
|
||||
public int UserExpirationMinutes { get; set; } = 15;
|
||||
|
||||
/// <summary>
|
||||
/// 订单缓存过期时间(分钟)
|
||||
/// </summary>
|
||||
public int OrderExpirationMinutes { get; set; } = 10;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用响应缓存
|
||||
/// </summary>
|
||||
public bool EnableResponseCaching { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用分布式缓存
|
||||
/// </summary>
|
||||
public bool EnableDistributedCaching { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 获取默认过期时间跨度
|
||||
/// </summary>
|
||||
public TimeSpan DefaultExpiration => TimeSpan.FromMinutes(DefaultExpirationMinutes);
|
||||
|
||||
/// <summary>
|
||||
/// 获取系统配置过期时间跨度
|
||||
/// </summary>
|
||||
public TimeSpan SystemConfigExpiration => TimeSpan.FromMinutes(SystemConfigExpirationMinutes);
|
||||
|
||||
/// <summary>
|
||||
/// 获取文章过期时间跨度
|
||||
/// </summary>
|
||||
public TimeSpan ArticleExpiration => TimeSpan.FromMinutes(ArticleExpirationMinutes);
|
||||
|
||||
/// <summary>
|
||||
/// 获取产品过期时间跨度
|
||||
/// </summary>
|
||||
public TimeSpan ProductExpiration => TimeSpan.FromMinutes(ProductExpirationMinutes);
|
||||
|
||||
/// <summary>
|
||||
/// 获取分类过期时间跨度
|
||||
/// </summary>
|
||||
public TimeSpan CategoryExpiration => TimeSpan.FromMinutes(CategoryExpirationMinutes);
|
||||
|
||||
/// <summary>
|
||||
/// 获取用户过期时间跨度
|
||||
/// </summary>
|
||||
public TimeSpan UserExpiration => TimeSpan.FromMinutes(UserExpirationMinutes);
|
||||
|
||||
/// <summary>
|
||||
/// 获取订单过期时间跨度
|
||||
/// </summary>
|
||||
public TimeSpan OrderExpiration => TimeSpan.FromMinutes(OrderExpirationMinutes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Redis缓存配置
|
||||
/// </summary>
|
||||
public class RedisCacheSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// 连接字符串
|
||||
/// </summary>
|
||||
public string ConnectionString { get; set; } = "server=127.0.0.1;password=;db=2";
|
||||
|
||||
/// <summary>
|
||||
/// 实例名称
|
||||
/// </summary>
|
||||
public string InstanceName { get; set; } = "COMCMS:";
|
||||
|
||||
/// <summary>
|
||||
/// 默认数据库
|
||||
/// </summary>
|
||||
public int DefaultDatabase { get; set; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// 连接超时时间(毫秒)
|
||||
/// </summary>
|
||||
public int ConnectTimeout { get; set; } = 5000;
|
||||
|
||||
/// <summary>
|
||||
/// 同步超时时间(毫秒)
|
||||
/// </summary>
|
||||
public int SyncTimeout { get; set; } = 5000;
|
||||
|
||||
/// <summary>
|
||||
/// 是否中断连接
|
||||
/// </summary>
|
||||
public bool AbortConnect { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// 连接重试次数
|
||||
/// </summary>
|
||||
public int ConnectRetry { get; set; } = 3;
|
||||
}
|
||||
}
|
||||
@@ -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<CacheSettings> settings)
|
||||
{
|
||||
_cacheProvider = cacheProvider;
|
||||
_settings = settings.Value;
|
||||
_prefix = Utils.PrefixKey ?? "comcms:";
|
||||
}
|
||||
|
||||
private string BuildKey(string key) => string.Concat(_prefix, key ?? string.Empty);
|
||||
|
||||
public async Task<T> GetAsync<T>(string key)
|
||||
{
|
||||
return await Task.FromResult(_cacheProvider.Cache.Get<T>(BuildKey(key)));
|
||||
}
|
||||
|
||||
public async Task SetAsync<T>(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<bool> ExistsAsync(string key)
|
||||
{
|
||||
var val = _cacheProvider.Cache.Get<object>(BuildKey(key));
|
||||
return await Task.FromResult(val != null);
|
||||
}
|
||||
|
||||
public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiration = null)
|
||||
{
|
||||
var cacheKey = BuildKey(key);
|
||||
var existed = _cacheProvider.Cache.Get<T>(cacheKey);
|
||||
if (!EqualityComparer<T>.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<object>(cacheKey);
|
||||
if (val != null) _cacheProvider.Cache.Add(cacheKey, val, (int)expiration.TotalSeconds);
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task<long> GetCacheSizeAsync()
|
||||
{
|
||||
// 暂无法获取容量,返回0
|
||||
return await Task.FromResult(0L);
|
||||
}
|
||||
|
||||
public async Task ClearAllAsync()
|
||||
{
|
||||
// 暂不提供全清功能
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace COMCMS.Web.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 缓存服务接口
|
||||
/// </summary>
|
||||
public interface ICacheService
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取缓存值
|
||||
/// </summary>
|
||||
/// <typeparam name="T">数据类型</typeparam>
|
||||
/// <param name="key">缓存键</param>
|
||||
/// <returns>缓存值</returns>
|
||||
Task<T> GetAsync<T>(string key);
|
||||
|
||||
/// <summary>
|
||||
/// 设置缓存值
|
||||
/// </summary>
|
||||
/// <typeparam name="T">数据类型</typeparam>
|
||||
/// <param name="key">缓存键</param>
|
||||
/// <param name="value">缓存值</param>
|
||||
/// <param name="expiration">过期时间</param>
|
||||
/// <returns></returns>
|
||||
Task SetAsync<T>(string key, T value, TimeSpan? expiration = null);
|
||||
|
||||
/// <summary>
|
||||
/// 移除缓存
|
||||
/// </summary>
|
||||
/// <param name="key">缓存键</param>
|
||||
/// <returns></returns>
|
||||
Task RemoveAsync(string key);
|
||||
|
||||
/// <summary>
|
||||
/// 根据模式移除缓存
|
||||
/// </summary>
|
||||
/// <param name="pattern">模式</param>
|
||||
/// <returns></returns>
|
||||
Task RemoveByPatternAsync(string pattern);
|
||||
|
||||
/// <summary>
|
||||
/// 检查缓存是否存在
|
||||
/// </summary>
|
||||
/// <param name="key">缓存键</param>
|
||||
/// <returns></returns>
|
||||
Task<bool> ExistsAsync(string key);
|
||||
|
||||
/// <summary>
|
||||
/// 获取或设置缓存
|
||||
/// </summary>
|
||||
/// <typeparam name="T">数据类型</typeparam>
|
||||
/// <param name="key">缓存键</param>
|
||||
/// <param name="factory">数据工厂方法</param>
|
||||
/// <param name="expiration">过期时间</param>
|
||||
/// <returns></returns>
|
||||
Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> factory, TimeSpan? expiration = null);
|
||||
|
||||
/// <summary>
|
||||
/// 刷新缓存过期时间
|
||||
/// </summary>
|
||||
/// <param name="key">缓存键</param>
|
||||
/// <param name="expiration">过期时间</param>
|
||||
/// <returns></returns>
|
||||
Task RefreshAsync(string key, TimeSpan expiration);
|
||||
|
||||
/// <summary>
|
||||
/// 获取缓存大小
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task<long> GetCacheSizeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 清空所有缓存
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
Task ClearAllAsync();
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -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<CacheSettings>(Configuration.GetSection("CacheSettings"));
|
||||
// 响应缓存
|
||||
services.AddResponseCaching();
|
||||
services.AddSingleton<ICacheProvider, RedisCacheProvider>();
|
||||
// 缓存服务封装
|
||||
services.AddSingleton<ICacheService, CacheService>();
|
||||
//部分系统配置
|
||||
services.Configure<SystemSetting>(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();
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -7,23 +7,23 @@
|
||||
<!--SQL目录。设置SQL输出的单独目录,默认为空,SQL输出到当前日志中。生产环境建议输出到站点外单独的SqlLog目录-->
|
||||
<SQLPath></SQLPath>
|
||||
<!--SQL执行时间。跟踪SQL执行时间,大于该阀值将输出日志,默认1000毫秒-->
|
||||
<TraceSQLTime>1000</TraceSQLTime>
|
||||
<TraceSQLTime>2000</TraceSQLTime>
|
||||
<!--SQL最大长度。输出日志时的SQL最大长度,超长截断,默认4096,不截断用0-->
|
||||
<SQLMaxLength>4096</SQLMaxLength>
|
||||
<!--参数化添删改查。默认关闭-->
|
||||
<UseParameter>false</UseParameter>
|
||||
<UseParameter>true</UseParameter>
|
||||
<!--命令超时。查询执行超时时间,默认0秒不限制-->
|
||||
<CommandTimeout>0</CommandTimeout>
|
||||
<CommandTimeout>30</CommandTimeout>
|
||||
<!--失败重试。执行命令超时后的重试次数,默认0不重试-->
|
||||
<RetryOnFailure>0</RetryOnFailure>
|
||||
<RetryOnFailure>3</RetryOnFailure>
|
||||
<!--数据层缓存。根据sql做缓存,默认0秒-->
|
||||
<DataCacheExpire>0</DataCacheExpire>
|
||||
<DataCacheExpire>300</DataCacheExpire>
|
||||
<!--实体缓存过期。整表缓存实体列表,默认10秒-->
|
||||
<EntityCacheExpire>10</EntityCacheExpire>
|
||||
<EntityCacheExpire>600</EntityCacheExpire>
|
||||
<!--单对象缓存过期。按主键缓存实体,默认10秒-->
|
||||
<SingleCacheExpire>10</SingleCacheExpire>
|
||||
<SingleCacheExpire>600</SingleCacheExpire>
|
||||
<!--扩展属性过期。扩展属性Extends缓存,默认10秒-->
|
||||
<ExtendExpire>10</ExtendExpire>
|
||||
<ExtendExpire>300</ExtendExpire>
|
||||
<!--反向工程。Off 关闭;ReadOnly 只读不执行;On 打开,仅新建;Full 完全,修改删除-->
|
||||
<Migration>On</Migration>
|
||||
<!--表名称、字段名大小写格式。Default 根据模型生成;Upper 全大写;Lower 全小写;Underline下划线-->
|
||||
|
||||
Reference in New Issue
Block a user