using Mapster; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Configuration; using Volo.Abp.Application.Services; using Volo.Abp.Caching; using Yi.Framework.AiHub.Application.Contracts.Dtos.Announcement; using Yi.Framework.AiHub.Application.Contracts.IServices; using Yi.Framework.AiHub.Domain.Entities; using Yi.Framework.SqlSugarCore.Abstractions; namespace Yi.Framework.AiHub.Application.Services; /// /// 公告服务 /// public class AnnouncementService : ApplicationService, IAnnouncementService { private readonly ISqlSugarRepository _announcementRepository; private readonly IConfiguration _configuration; private readonly IDistributedCache _announcementCache; private const string AnnouncementCacheKey = "AiHub:Announcement"; public AnnouncementService( ISqlSugarRepository announcementRepository, IConfiguration configuration, IDistributedCache announcementCache) { _announcementRepository = announcementRepository; _configuration = configuration; _announcementCache = announcementCache; } /// /// 获取公告信息 /// public async Task> GetAsync() { // 使用 GetOrAddAsync 从缓存获取或添加数据,缓存1小时 var cacheData = await _announcementCache.GetOrAddAsync( AnnouncementCacheKey, async () => await LoadAnnouncementDataAsync(), () => new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1) } ); return cacheData?.Logs ?? new List(); } /// /// 从数据库加载公告数据 /// private async Task LoadAnnouncementDataAsync() { // 查询所有公告日志,按日期降序排列 var logs = await _announcementRepository._DbQueryable .OrderByDescending(x => x.StartTime) .ToListAsync(); // 转换为 DTO var logDtos = logs.Adapt>(); return new AnnouncementCacheDto { Logs = logDtos }; } }