diff --git a/src/0-core/HuanMeng.DotNetCore/HuanMeng.DotNetCore.csproj b/src/0-core/HuanMeng.DotNetCore/HuanMeng.DotNetCore.csproj index 1aafa90..7e12d3d 100644 --- a/src/0-core/HuanMeng.DotNetCore/HuanMeng.DotNetCore.csproj +++ b/src/0-core/HuanMeng.DotNetCore/HuanMeng.DotNetCore.csproj @@ -11,11 +11,15 @@ + + + + diff --git a/src/0-core/HuanMeng.DotNetCore/MiddlewareExtend/CacheMiddleware.cs b/src/0-core/HuanMeng.DotNetCore/MiddlewareExtend/CacheMiddleware.cs new file mode 100644 index 0000000..9d33617 --- /dev/null +++ b/src/0-core/HuanMeng.DotNetCore/MiddlewareExtend/CacheMiddleware.cs @@ -0,0 +1,102 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.AspNetCore.Http.Features; +namespace HuanMeng.DotNetCore.MiddlewareExtend +{ + public class CacheMiddleware + { + private readonly RequestDelegate _next; + private readonly IMemoryCache _cache; + + public CacheMiddleware(RequestDelegate next, IMemoryCache cache) + { + _next = next; + _cache = cache; + } + + public async Task InvokeAsync(HttpContext context) + { + // 检查当前请求是否需要缓存 + var cacheAttribute = GetCacheAttribute(context); + if (cacheAttribute == null) + { + // 如果没有找到 CacheAttribute,直接调用下一个中间件 + await _next(context); + return; + } + + // 生成缓存键(基于请求路径和查询字符串) + var cacheKey = GenerateCacheKey(context.Request); + + // 尝试从缓存中获取数据 + if (_cache.TryGetValue(cacheKey, out string cachedResponse)) + { + // 如果缓存中有数据,则直接返回缓存的响应 + context.Response.ContentType = "application/json"; + await context.Response.WriteAsync(cachedResponse); + return; + } + + // 捕获原始响应流 + var originalResponseStream = context.Response.Body; + + try + { + using (var memoryStream = new MemoryStream()) + { + context.Response.Body = memoryStream; + + // 调用下一个中间件 + await _next(context); + + // 将响应流重新定位到起始位置 + memoryStream.Position = 0; + + // 读取响应内容 + var responseBody = await new StreamReader(memoryStream).ReadToEndAsync(); + + // 将响应内容缓存 + _cache.Set(cacheKey, responseBody, TimeSpan.FromSeconds(cacheAttribute.DurationInSeconds)); + + // 将内容写回原始响应流 + memoryStream.Position = 0; + await memoryStream.CopyToAsync(originalResponseStream); + } + } + finally + { + // 恢复原始响应流 + context.Response.Body = originalResponseStream; + } + } + + private CacheAttribute GetCacheAttribute(HttpContext context) + { + var endpoint = context.Features.Get()?.Endpoint; + //var endpoint = context.GetEndpoint(); + if (endpoint == null) return null; + + // 检查控制器和操作方法上是否有 CacheAttribute + var attribute = endpoint.Metadata.GetMetadata(); + return attribute; + } + + private string GenerateCacheKey(HttpRequest request) + { + // 基于请求路径和查询参数生成缓存键 + var cacheKey = $"{request.Path}{request.QueryString}"; + return cacheKey; + } + } + + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + public class CacheAttribute : Attribute + { + public int DurationInSeconds { get; } + + public CacheAttribute(int durationInSeconds) + { + DurationInSeconds = durationInSeconds; + } + } +} diff --git a/src/0-core/HuanMeng.MiaoYu.Code/Music/MusicBLL.cs b/src/0-core/HuanMeng.MiaoYu.Code/Music/MusicBLL.cs index 1973dd9..fd6808b 100644 --- a/src/0-core/HuanMeng.MiaoYu.Code/Music/MusicBLL.cs +++ b/src/0-core/HuanMeng.MiaoYu.Code/Music/MusicBLL.cs @@ -1,27 +1,13 @@ -using HuanMeng.MiaoYu.Code.Cache.Contract; -using HuanMeng.MiaoYu.Model.DbSqlServer.Db_MiaoYu; +using HuanMeng.MiaoYu.Code.Cache.Special; using HuanMeng.MiaoYu.Model.Dto.Music; +using HuanMeng.MiaoYu.Model.Dto.Shop; +using HuanMeng.MiaoYu.Model.EnumModel.Product; + +using Newtonsoft.Json; using StackExchange.Redis; -using System; -using System.Collections.Generic; -using System.Linq; using System.Net.Http.Headers; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json.Serialization; -using Newtonsoft.Json; -using HuanMeng.MiaoYu.Code.Chat.Contract; -using Org.BouncyCastle.Utilities; -using HuanMeng.MiaoYu.Code.Users; -using Org.BouncyCastle.Crypto; -using HuanMeng.MiaoYu.Model.Dto; -using HuanMeng.MiaoYu.Code.DataAccess; -using HuanMeng.MiaoYu.Code.Cache.Special; -using HuanMeng.MiaoYu.Model.Dto.Shop; -using HuanMeng.MiaoYu.Model.EnumModel.Product; namespace HuanMeng.MiaoYu.Code.Music { @@ -61,6 +47,12 @@ namespace HuanMeng.MiaoYu.Code.Music //图片 var genresList = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList(this, it => it.IsEnabled); var list = Mapper.Map>(genresList); + var obj = Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.IsPublic).GroupBy(it => it.GenreId).Select(it => new { GenreId = it.Key, Count = it.Count() }).ToList(); + if (obj != null) + { + list = list.Where(it => obj.Any(item => item.GenreId == it.Id)).ToList(); + } + list.Insert(0, new MusicGenresDto() { Id = 0, @@ -93,7 +85,7 @@ namespace HuanMeng.MiaoYu.Code.Music UserId = user.Id, UserIconUrl = string.IsNullOrEmpty(user?.UserIconUrl) ? "https://cos.shhuanmeng.com/default.png" : user?.UserIconUrl, Vip = songVipInfo.isVip ? 1 : 0, - VipExpirationAt= songVipInfo.expirationAt, + VipExpirationAt = songVipInfo.expirationAt, DownloadCount = info.DownloadCount, LikeCount = info.LikeCount, PlayCount = info.PlayCount, @@ -404,7 +396,9 @@ namespace HuanMeng.MiaoYu.Code.Music await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "歌曲已公开", true); } - songs.State = 2; + //songs.State = 2; + songs.State = 3; + songs.IsPublic = true; await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "歌曲已提交审核", true); } diff --git a/src/2-api/HuanMeng.MiaoYu.WebApi/Controllers/MusicController.cs b/src/2-api/HuanMeng.MiaoYu.WebApi/Controllers/MusicController.cs index 33187f5..f8b7d69 100644 --- a/src/2-api/HuanMeng.MiaoYu.WebApi/Controllers/MusicController.cs +++ b/src/2-api/HuanMeng.MiaoYu.WebApi/Controllers/MusicController.cs @@ -1,4 +1,5 @@ using HuanMeng.DotNetCore.Base; +using HuanMeng.DotNetCore.MiddlewareExtend; using HuanMeng.MiaoYu.Code.Cache; using HuanMeng.MiaoYu.Code.Cache.Special; using HuanMeng.MiaoYu.Code.Music; @@ -33,6 +34,7 @@ namespace HuanMeng.MiaoYu.WebApi.Controllers /// [HttpGet] [AllowAnonymous] + [Cache(60 * 5)] public async Task>> GetMusicGenresList() { MusicBLL musicBLL = new MusicBLL(ServiceProvider); diff --git a/src/2-api/HuanMeng.MiaoYu.WebApi/Program.cs b/src/2-api/HuanMeng.MiaoYu.WebApi/Program.cs index 5bb55c5..e083a70 100644 --- a/src/2-api/HuanMeng.MiaoYu.WebApi/Program.cs +++ b/src/2-api/HuanMeng.MiaoYu.WebApi/Program.cs @@ -62,6 +62,7 @@ builder.Services.AddSingleton(typeof(ILogger), serviceProvi // 检索程序集信息 AssemblyInfo assemblyInfo = AssemblyInfoHelper.GetAssemblyInfo(); // Add services to the container. +builder.Services.AddMemoryCache(); builder.Services.AddHttpClient(); builder.Services.AddHttpContextAccessor(); //添加httpContext注入访问 #region 添加跨域 @@ -182,7 +183,8 @@ app.UseStaticFiles();//静态文件访问配置 app.UseMultiTenantMiaoYu(); //执行扩展中间件 app.UseMiddlewareAll(); - +// 使用缓存中间件 +app.UseMiddleware(); #region 默认请求 app.MapGet("/", () => "请求成功").WithName("默认请求");