using Volo.Abp.Application.Dtos; using Volo.Abp.Caching; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Repositories; using Volo.Abp.MultiTenancy; namespace Yi.Framework.Ddd.Application { /// /// 带缓存的CRUD应用服务基类 /// /// 实体类型 /// 实体DTO类型 /// 主键类型 public abstract class YiCacheCrudAppService : YiCrudAppService where TEntity : class, IEntity where TEntityDto : IEntityDto { protected YiCacheCrudAppService(IRepository repository) : base(repository) { } } public abstract class YiCacheCrudAppService : YiCrudAppService where TEntity : class, IEntity where TEntityDto : IEntityDto { protected YiCacheCrudAppService(IRepository repository) : base(repository) { } } public abstract class YiCacheCrudAppService : YiCrudAppService where TEntity : class, IEntity where TEntityDto : IEntityDto { protected YiCacheCrudAppService(IRepository repository) : base(repository) { } } public abstract class YiCacheCrudAppService : YiCrudAppService where TEntity : class, IEntity where TEntityDto : IEntityDto { protected YiCacheCrudAppService(IRepository repository) : base(repository) { } } /// /// 完整的带缓存CRUD应用服务实现 /// public abstract class YiCacheCrudAppService : YiCrudAppService where TEntity : class, IEntity where TGetOutputDto : IEntityDto where TGetListOutputDto : IEntityDto { /// /// 分布式缓存访问器 /// private IDistributedCache EntityCache => LazyServiceProvider.LazyGetRequiredService>(); /// /// 获取缓存键 /// protected virtual string GenerateCacheKey(TKey id) => $"{typeof(TEntity).Name}:{CurrentTenant.Id ?? Guid.Empty}:{id}"; protected YiCacheCrudAppService(IRepository repository) : base(repository) { } /// /// 更新实体并清除缓存 /// public override async Task UpdateAsync(TKey id, TUpdateInput input) { var result = await base.UpdateAsync(id, input); await EntityCache.RemoveAsync(GenerateCacheKey(id)); return result; } /// /// 获取实体列表(需要继承实现具体的缓存策略) /// public override Task> GetListAsync(TGetListInput input) { // 建议实现两种缓存策略: // 1. 全表缓存: 适用于数据量小且变动不频繁的场景 // 2. 按需缓存: 仅缓存常用数据,适用于大数据量场景 throw new NotImplementedException("请实现具体的缓存查询策略"); } /// /// 从数据库获取实体列表 /// protected virtual Task> GetListFromDatabaseAsync( TGetListInput input) { throw new NotImplementedException(); } /// /// 从缓存获取实体列表 /// protected virtual Task> GetListFromCacheAsync( TGetListInput input) { throw new NotImplementedException(); } /// /// 获取单个实体(优先从缓存获取) /// protected override async Task GetEntityByIdAsync(TKey id) { return (await EntityCache.GetOrAddAsync( GenerateCacheKey(id), async () => await base.GetEntityByIdAsync(id)))!; } /// /// 批量删除实体并清除缓存 /// public override async Task DeleteAsync(IEnumerable ids) { await base.DeleteAsync(ids); // 批量清除缓存 var tasks = ids.Select(id => EntityCache.RemoveAsync(GenerateCacheKey(id))); await Task.WhenAll(tasks); } } }