造輪子之設定管理

2023-10-19 12:00:12

前面我們基礎設施基本搭建完畢,後面可以做一些稍微複雜點的功能了,接下來就來實現一個設定管理。
設定管理一般用做一些系統設定之類的,如郵箱設定等,面向使用人員。而不需要修改我們的組態檔,修改組態檔的方式就偏向於技術人員了。
話不多說,開造。

設計結構

設定管理中需要2個表,一個是設定組表,比如什麼郵箱設定是一個分組,公眾號設定是一個分組。一個是設定的值的儲存表,用作儲存分組的設定。

using Wheel.Domain.Common;

namespace Wheel.Domain.Settings
{
    public class SettingGroup : Entity
    {
        public string Name { get; set; }
        public string NormalizedName { get; set; }

        public virtual ICollection<SettingValue> SettingValues { get; set; }
    }
}
using Wheel.Domain.Common;
using Wheel.Enums;

namespace Wheel.Domain.Settings
{
    public class SettingValue : Entity
    {
        public virtual long SettingGroupId { get; set; }
        public virtual SettingGroup SettingGroup { get; set; }
        public string Key { get; set; }
        public string Value { get; set; }
        public SettingValueType ValueType { get; set; }
        public SettingScope SettingScope { get; set; }
        public string? SettingScopeKey { get; set; }
    }
}

這裡有兩個列舉值,分別是SettingValueType和SettingScope
SettingValueType是Value的型別,如字串,布林值,整型,浮點數,主要用於配合前端做頁面展示格式以及修改設定時的資料校驗。
SettingScope表示設定的生效範圍,比如全域性設定,使用者設定等等,SettingScopeKey則用作儲存範圍關聯的鍵值,比如使用者範圍的話,SettingScopeKey就約定存UserId作為鍵值,當然也可以自己約定別的唯一數用作關聯。後續都可以擴充套件。

namespace Wheel.Enums
{
    public enum SettingValueType
    {
        /// <summary>
        /// 布林值
        /// </summary>
        Bool,
        /// <summary>
        /// 整型
        /// </summary>
        Int,
        /// <summary>
        /// 長整型
        /// </summary>
        Long,
        /// <summary>
        /// 64位元雙精度浮點型
        /// </summary>
        Double,
        /// <summary>
        /// 128位元精確的十進位制值
        /// </summary>
        Decimal,
        /// <summary>
        /// 字串
        /// </summary>
        String,
        /// <summary>
        /// Json物件
        /// </summary>
        JsonObject
    }
}
namespace Wheel.Enums
{
    public enum SettingScope
    {
        /// <summary>
        /// 全域性設定
        /// </summary>
        Golbal,
        /// <summary>
        /// 使用者設定
        /// </summary>
        User,
    }
}

修改DbContext

在DbContext中新增程式碼

#region Setting
public DbSet<SettingGroup> SettingGroups { get; set; }
public DbSet<SettingValue> SettingValues { get; set; }
#endregion

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    ConfigureIdentity(builder);
    ConfigureLocalization(builder);
    ConfigurePermissionGrants(builder);
    ConfigureMenus(builder);
    ConfigureSettings(builder);
}

void ConfigureSettings(ModelBuilder builder)
{
    builder.Entity<SettingGroup>(b =>
    {
        b.HasKey(o => o.Id);
        b.Property(o => o.Name).HasMaxLength(128);
        b.Property(o => o.NormalizedName).HasMaxLength(128);
        b.HasMany(o => o.SettingValues).WithOne(o => o.SettingGroup);
        b.HasIndex(o => o.Name);
    });
    builder.Entity<SettingValue>(b =>
    {
        b.HasKey(o => o.Id);
        b.Property(o => o.Key).HasMaxLength(128);
        b.Property(o => o.SettingScopeKey).HasMaxLength(128);
        b.Property(o => o.ValueType).HasMaxLength(2048);
        b.HasOne(o => o.SettingGroup).WithMany(o => o.SettingValues);
        b.HasIndex(o => o.Key);
    });
}

然後執行資料庫遷移命令修改資料庫即可。

SettingManager

接下來實現一個SettingManager用於管理設定。

using HotChocolate.Types.Relay;
using System;
using System.Linq;
using Wheel.DependencyInjection;
using Wheel.Enums;
using Wheel.EventBus.Distributed;
using Wheel.EventBus.EventDatas;
using Wheel.Uow;
using Wheel.Utilities;

namespace Wheel.Domain.Settings
{
    public class SettingManager : ITransientDependency
    {
        private readonly IBasicRepository<SettingGroup, long> _settingGroupRepository;
        private readonly IBasicRepository<SettingValue, long> _settingValueRepository;

        private readonly IUnitOfWork _unitOfWork;
        private readonly SnowflakeIdGenerator _snowflakeIdGenerator;
        private readonly IDistributedEventBus _distributedEventBus;

        public SettingManager(IBasicRepository<SettingGroup, long> settingGroupRepository, IBasicRepository<SettingValue, long> settingValueRepository, IUnitOfWork unitOfWork, SnowflakeIdGenerator snowflakeIdGenerator, IDistributedEventBus distributedEventBus)
        {
            _settingGroupRepository = settingGroupRepository;
            _settingValueRepository = settingValueRepository;
            _unitOfWork = unitOfWork;
            _snowflakeIdGenerator = snowflakeIdGenerator;
            _distributedEventBus = distributedEventBus;
        }

        public async Task<T?> GetSettingValue<T>(string settingGroupName, string settingKey, SettingScope settingScope = SettingScope.Golbal, string? settingScopeKey = null, CancellationToken cancellationToken = default)
        {
            var settingGroup = await _settingGroupRepository.FindAsync(a => a.Name == settingGroupName, cancellationToken);

            if (settingGroup is null)
            {
                throw new ArgumentException($"SettingGroup: {settingGroup} Not Exist.");
            }

            var settingValue = settingGroup?.SettingValues.FirstOrDefault(a => a.Key == settingKey && a.SettingScope == settingScope && a.SettingScopeKey == settingScopeKey);

            if (settingValue is null)
                return default;

            if(settingValue.ValueType == SettingValueType.JsonObject)
                return settingValue.Value.ToObject<T>();

            return (T)Convert.ChangeType(settingValue, typeof(T));
        }

        public async Task<SettingValue?> GetSettingValue(string settingGroupName, string settingKey, SettingScope settingScope = SettingScope.Golbal, string? settingScopeKey = null, CancellationToken cancellationToken = default)
        {
            var settingGroup = await _settingGroupRepository.FindAsync(a => a.Name == settingGroupName, cancellationToken);

            if (settingGroup is null)
            {
                throw new ArgumentException($"SettingGroup: {settingGroup} Not Exist.");
            }

            var settingValue = settingGroup?.SettingValues.FirstOrDefault(a => a.Key == settingKey && a.SettingScope == settingScope && a.SettingScopeKey == settingScopeKey);
            
            return settingValue;
        }

        public async Task<List<SettingValue>?> GetSettingValues(string settingGroupName, SettingScope settingScope = SettingScope.Golbal, string? settingScopeKey = null, CancellationToken cancellationToken = default)
        {
            var settingGroup = await _settingGroupRepository.FindAsync(a => a.Name == settingGroupName, cancellationToken);

            if (settingGroup is null)
            {
                throw new ArgumentException($"SettingGroup: {settingGroup} Not Exist.");
            }

            var settingValues = settingGroup?.SettingValues.Where(a => a.SettingScope == settingScope && a.SettingScopeKey == settingScopeKey).ToList();

            return settingValues;
        }

        public async Task SetSettingValue(string settingGroupName, SettingValue settingValue, CancellationToken cancellationToken = default)
        {
            using (var uow = await _unitOfWork.BeginTransactionAsync(cancellationToken))
            {
                try
                {
                    var settingGroup = await _settingGroupRepository.FindAsync(a => a.Name == settingGroupName, cancellationToken);
                    if (settingGroup is null)
                        settingGroup = await _settingGroupRepository.InsertAsync(new SettingGroup { Id = _snowflakeIdGenerator.Create(), Name = settingGroupName, NormalizedName = settingGroupName.ToUpper() }, cancellationToken: cancellationToken);
                    

                    CheckSettingValueType(settingValue.Value, settingValue.ValueType);

                    var sv = await _settingValueRepository.FindAsync(a=> a.SettingGroupId == settingGroup.Id && a.Id == settingValue.Id, cancellationToken);
                    if(sv is null)
                    {
                        settingValue.Id = _snowflakeIdGenerator.Create();
                        settingValue.SettingGroupId = settingGroup.Id;
                        await _settingValueRepository.InsertAsync(settingValue, cancellationToken: cancellationToken);
                    }
                    else
                        await _settingValueRepository.UpdateAsync(settingValue, cancellationToken: cancellationToken);
                    
                    await uow.CommitAsync(cancellationToken);
                    await _distributedEventBus.PublishAsync(new UpdateSettingEventData() { GroupName = settingGroupName, SettingScope = settingValue.SettingScope, SettingScopeKey = settingValue.SettingScopeKey });
                }
                catch(Exception ex)
                {
                    await uow.RollbackAsync(cancellationToken);
                    ex.ReThrow();
                }
            }
        }
        public async Task SetSettingValues(string settingGroupName, List<SettingValue> settingValues, CancellationToken cancellationToken = default)
        {
            using (var uow = await _unitOfWork.BeginTransactionAsync(cancellationToken))
            {
                try
                {
                    var settingGroup = await _settingGroupRepository.FindAsync(a => a.Name == settingGroupName, cancellationToken);
                    if (settingGroup is null)
                        settingGroup = await _settingGroupRepository.InsertAsync(new SettingGroup { Id = _snowflakeIdGenerator.Create(), Name = settingGroupName, NormalizedName = settingGroupName.ToUpper() }, true, cancellationToken: cancellationToken);

                    foreach (var settingValue in settingValues)
                    {
                        CheckSettingValueType(settingValue.Value, settingValue.ValueType);

                        var sv = await _settingValueRepository.FindAsync(a => a.SettingGroupId == settingGroup.Id && a.Id == settingValue.Id, cancellationToken);
                        if (sv is null)
                        {
                            settingValue.Id = _snowflakeIdGenerator.Create();
                            settingValue.SettingGroupId = settingGroup.Id;
                            await _settingValueRepository.InsertAsync(settingValue, cancellationToken: cancellationToken);
                        }
                        else
                            await _settingValueRepository.UpdateAsync(settingValue, cancellationToken: cancellationToken);
                    }
                    
                    await uow.CommitAsync(cancellationToken);
                    await _distributedEventBus.PublishAsync(new UpdateSettingEventData() { GroupName = settingGroupName, SettingScope = settingValues.First().SettingScope, SettingScopeKey = settingValues.First().SettingScopeKey });
                }
                catch (Exception ex)
                {
                    await uow.RollbackAsync(cancellationToken);
                    ex.ReThrow();
                }
            }
        }

        private void CheckSettingValueType(string settingValue, SettingValueType settingValueType)
        {
            switch (settingValueType)
            {
                case SettingValueType.String:
                case SettingValueType.JsonObject:
                    return;
                case SettingValueType.Bool:
                    if(bool.TryParse(settingValue, out var _))
                    {
                        return;
                    }
                    else
                    {
                        throw new ArgumentException($"SettingValue: {settingValue} Can Not Parse To Bool Type");
                    }
                case SettingValueType.Int:
                    if (int.TryParse(settingValue, out var _))
                    {
                        return;
                    }
                    else
                    {
                        throw new ArgumentException($"SettingValue: {settingValue} Can Not Parse To Int Type");
                    }
                case SettingValueType.Long:
                    if (long.TryParse(settingValue, out var _))
                    {
                        return;
                    }
                    else
                    {
                        throw new ArgumentException($"SettingValue: {settingValue} Can Not Parse To Long Type");
                    }
                case SettingValueType.Double:
                    if (double.TryParse(settingValue, out var _))
                    {
                        return;
                    }
                    else
                    {
                        throw new ArgumentException($"SettingValue: {settingValue} Can Not Parse To Double Type");
                    }
                case SettingValueType.Decimal:
                    if (decimal.TryParse(settingValue, out var _))
                    {
                        return;
                    }
                    else
                    {
                        throw new ArgumentException($"SettingValue: {settingValue} Can Not Parse To Decimal Type");
                    }
            }
        }
    }
}

這裡CheckSettingValueType就是根據SettingValueType做資料校驗,如果不符合條件的則拒絕修改。
就這樣,資料庫的設定管理操作基本完成。

SettingDefinition

資料庫完成之後,接下來就是業務層面的事情了,這裡我們定義一個ISettingDefinition介面,用作設定組結構的基本定義和作用範圍,比如我們郵箱設定裡面包含什麼引數值,型別,預設值是什麼。
ISettingDefinition:

using Wheel.DependencyInjection;
using Wheel.Enums;

namespace Wheel.Settings
{
    public interface ISettingDefinition : ITransientDependency
    {
        string GroupName { get; }
        SettingScope SettingScope { get; }

        ValueTask<Dictionary<string, SettingValueParams>> Define();
    }
}

EmailSettingDefinition:

using Wheel.Enums;

namespace Wheel.Settings.Email
{
    public class EmailSettingDefinition : ISettingDefinition
    {
        public string GroupName => "EmailSetting";

        public SettingScope SettingScope => SettingScope.Golbal;

        public ValueTask<Dictionary<string, SettingValueParams>> Define()
        {
            return ValueTask.FromResult(new Dictionary<string, SettingValueParams>
            {
                { "SenderName", new(SettingValueType.String, "Wheel") },
                { "Host", new(SettingValueType.String, "smtp.exmail.qq.com") },
                { "Prot", new(SettingValueType.Int, "465") },
                { "UserName", new(SettingValueType.String) },
                { "Password", new(SettingValueType.String) },
                { "UseSsl", new(SettingValueType.Bool, "true") },
            });
        }
    }
}
public record SettingValueParams(SettingValueType SettingValueType, string? DefalutValue = null, string? SettingScopeKey = null);

可以看到這裡郵件的設定定義:
GroupName指定是EmailSetting這個分組。
SettingScope指定了是全域性範圍的設定。
SettingValueParams是一個record結構,包含設定值的型別,預設值以及範圍的Key值。
Define裡面是一個字典結構,裡面定義的郵件傳送設定裡面所需要的所有引數以及預設值。

SettingDefinition的作用更多在於當資料庫沒有儲存資料時,作為一個預設的結構以及預設值取用。

SettingManageAppService

接下來就需要提供API給使用者端互動了,兩個介面即可滿足,一個用於獲取設定,一個用於修改設定。
ISettingManageAppService:

using Wheel.Core.Dto;
using Wheel.DependencyInjection;
using Wheel.Enums;
using Wheel.Services.SettingManage.Dtos;

namespace Wheel.Services.SettingManage
{
    public interface ISettingManageAppService : ITransientDependency
    {
        Task<R<List<SettingGroupDto>>> GetAllSettingGroup(SettingScope settingScope = SettingScope.Golbal);
        Task<R> UpdateSettings(SettingGroupDto settingGroupDto, SettingScope settingScope = SettingScope.Golbal);
    }
}

SettingManageAppService:

using Wheel.Core.Dto;
using Wheel.Domain.Settings;
using Wheel.Domain;
using Wheel.Enums;
using Wheel.Services.SettingManage.Dtos;
using Wheel.Settings;

namespace Wheel.Services.SettingManage
{
    public class SettingManageAppService : WheelServiceBase, ISettingManageAppService
    {
        private readonly IBasicRepository<SettingGroup, long> _settingGroupRepository;
        private readonly IBasicRepository<SettingValue, long> _settingValueRepository;
        private readonly SettingManager _settingManager;

        public SettingManageAppService(IBasicRepository<SettingGroup, long> settingGroupRepository, IBasicRepository<SettingValue, long> settingValueRepository, SettingManager settingManager)
        {
            _settingGroupRepository = settingGroupRepository;
            _settingValueRepository = settingValueRepository;
            _settingManager = settingManager;
        }

        public async Task<R<List<SettingGroupDto>>> GetAllSettingGroup(SettingScope settingScope = SettingScope.Golbal)
        {
            var settingDefinitions = ServiceProvider.GetServices<ISettingDefinition>().Where(a => a.SettingScope == settingScope);
            var settingGroups = await _settingGroupRepository.GetListAsync(a => a.SettingValues.Any(a => a.SettingScope == settingScope && (settingScope == SettingScope.User ? a.SettingScopeKey == CurrentUser.Id : a.SettingScopeKey == null)));
            foreach (var settingDefinition in settingDefinitions)
            {
                if (settingGroups.Any(a => a.Name == settingDefinition.GroupName))
                    continue;
                else
                {
                    var group = new SettingGroup
                    {
                        Name = settingDefinition.GroupName,
                        NormalizedName = settingDefinition.GroupName.ToUpper(),
                        SettingValues = new List<SettingValue>()
                    };
                    foreach (var settings in await settingDefinition.Define())
                    {
                        group.SettingValues.Add(new SettingValue 
                        {
                            Key = settings.Key,
                            Value = settings.Value.DefalutValue,
                            ValueType = settings.Value.SettingValueType,
                            SettingScopeKey = settings.Value.SettingScopeKey,
                            SettingScope = settingScope
                        });
                    }
                    settingGroups.Add(group);
                }
            }
            var settingGroupDtos = Mapper.Map<List<SettingGroupDto>>(settingGroups);
            return new R<List<SettingGroupDto>>(settingGroupDtos);
        }

        public async Task<R> UpdateSettings(SettingGroupDto settingGroupDto, SettingScope settingScope = SettingScope.Golbal)
        {
            var settings = Mapper.Map<List<SettingValue>>(settingGroupDto.SettingValues);
            settings.ForEach(a =>
            {
                a.SettingScope = settingScope;
                a.SettingScopeKey = settingScope == SettingScope.User ? CurrentUser.Id : null;
            });
            await _settingManager.SetSettingValues(settingGroupDto.Name, settings);
            return new R();
        }
    }
}

這裡可以看到GetAllSettingGroup的實現,當資料庫取值沒有改設定組資料時,獲取SettingDefinition的結構返回給使用者端。

SettingManageController

SettingManageController很簡單,就是包裝ISettingManageAppService暴露API出去即可。

using Microsoft.AspNetCore.Mvc;
using Wheel.Core.Dto;
using Wheel.Enums;
using Wheel.Services.SettingManage;
using Wheel.Services.SettingManage.Dtos;

namespace Wheel.Controllers
{
    /// <summary>
    /// 設定管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SettingManageController : WheelControllerBase
    {
        private readonly ISettingManageAppService _settingManageAppService;

        public SettingManageController(ISettingManageAppService settingManageAppService)
        {
            _settingManageAppService = settingManageAppService;
        }

        /// <summary>
        /// 獲取所有設定
        /// </summary>
        /// <param name="settingScope">設定範圍</param>
        /// <returns></returns>
        [HttpGet()]
        public Task<R<List<SettingGroupDto>>> GetAllSettingGroup(SettingScope settingScope = SettingScope.Golbal)
        {
            return _settingManageAppService.GetAllSettingGroup(settingScope);
        }
        /// <summary>
        /// 更新設定
        /// </summary>
        /// <param name="settingGroupDto">設定組資料</param>
        /// <param name="settingScope">設定範圍</param>
        /// <returns></returns>
        [HttpPut("{settingScope}")]
        public Task<R> UpdateSettings(SettingGroupDto settingGroupDto, SettingScope settingScope)
        {
            return _settingManageAppService.UpdateSettings(settingGroupDto, settingScope);
        }
    }
}

就這樣與使用者端的互動API完成了。

SettingProvider

接下來則是需要實現一個給內部業務獲取設定的工具。
SettingProvider用作程式內獲取對應設定。直接封裝獲取全域性設定或使用者設定。

using Wheel.DependencyInjection;

namespace Wheel.Settings
{
    public interface ISettingProvider : ITransientDependency
    {
        public Task<Dictionary<string, string>> GetGolbalSettings(string groupKey, CancellationToken cancellationToken = default);
        public Task<string> GetGolbalSetting(string groupKey, string settingKey, CancellationToken cancellationToken = default);
        public Task<T> GetGolbalSetting<T>(string groupKey, string settingKey, CancellationToken cancellationToken = default) where T : struct;

        public Task<Dictionary<string, string>> GetUserSettings(string groupKey, CancellationToken cancellationToken = default);
        public Task<string> GetUserSetting(string groupKey, string settingKey, CancellationToken cancellationToken = default);
        public Task<T> GetUserSetting<T>(string groupKey, string settingKey, CancellationToken cancellationToken = default) where T : struct;
    }
}
using Microsoft.Extensions.Caching.Distributed;
using Wheel.Core.Users;
using Wheel.Domain.Settings;
using Wheel.Enums;

namespace Wheel.Settings
{
    public class DefaultSettingProvider : ISettingProvider
    {
        private readonly SettingManager _settingManager;
        private readonly IDistributedCache _distributedCache;
        private readonly ICurrentUser _currentUser;
        private readonly IServiceProvider _serviceProvider;

        public DefaultSettingProvider(SettingManager settingManager, IDistributedCache distributedCache, ICurrentUser currentUser, IServiceProvider serviceProvider)
        {
            _settingManager = settingManager;
            _distributedCache = distributedCache;
            _currentUser = currentUser;
            _serviceProvider = serviceProvider;
        }

        public async Task<string> GetGolbalSetting(string groupKey, string settingKey, CancellationToken cancellationToken = default)
        {
            var settings = await GetGolbalSettings(groupKey, cancellationToken);
            return settings[settingKey];
        }

        public async Task<T> GetGolbalSetting<T>(string groupKey, string settingKey, CancellationToken cancellationToken = default) where T : struct
        {
            var settings = await GetGolbalSettings(groupKey, cancellationToken);
            return settings[settingKey].To<T>();
        }

        public async Task<Dictionary<string, string>> GetGolbalSettings(string groupKey, CancellationToken cancellationToken = default)
        {
            var cacheSettings = await GetCacheItem(groupKey, SettingScope.Golbal, cancellationToken: cancellationToken);
            if(cacheSettings is null)
            {
                var dbSettings = await _settingManager.GetSettingValues(groupKey, SettingScope.Golbal, cancellationToken: cancellationToken);
                if(dbSettings is null)
                {
                    var settingDefinition = _serviceProvider.GetServices<ISettingDefinition>().FirstOrDefault(a => a.GroupName == groupKey && a.SettingScope == SettingScope.Golbal);
                    if(settingDefinition is null)
                        return new();
                    else
                    {
                        var setting = await settingDefinition.Define();
                        return setting.ToDictionary(a => a.Key, a => a.Value.DefalutValue)!;
                    }
                }
                return dbSettings.ToDictionary(a => a.Key, a => a.Value);
            }
            else
            {
                return cacheSettings.ToDictionary(a => a.Key, a => a.Value);
            }
        }

        public async Task<string> GetUserSetting(string groupKey, string settingKey, CancellationToken cancellationToken = default)
        {
            var settings = await GetUserSettings(groupKey, cancellationToken);
            return settings[settingKey];
        }

        public async Task<T> GetUserSetting<T>(string groupKey, string settingKey, CancellationToken cancellationToken = default) where T : struct
        {
            var settings = await GetUserSettings(groupKey, cancellationToken);
            return settings[settingKey].To<T>();
        }

        public async Task<Dictionary<string, string>> GetUserSettings(string groupKey, CancellationToken cancellationToken = default)
        {
            var cacheSettings = await GetCacheItem(groupKey, SettingScope.User, settingScopeKey: _currentUser.Id, cancellationToken: cancellationToken);
            if (cacheSettings is null)
            {
                var dbSettings = await _settingManager.GetSettingValues(groupKey, SettingScope.User, settingScopeKey: _currentUser.Id, cancellationToken: cancellationToken);
                if (dbSettings is null)
                {
                    var settingDefinition = _serviceProvider.GetServices<ISettingDefinition>().FirstOrDefault(a => a.GroupName == groupKey && a.SettingScope == SettingScope.User);
                    if (settingDefinition is null)
                        return new();
                    else
                    {
                        var setting = await settingDefinition.Define();
                        return setting.ToDictionary(a => a.Key, a => a.Value.DefalutValue)!;
                    }
                }
                return dbSettings.ToDictionary(a => a.Key, a => a.Value);
            }
            else
            {
                return cacheSettings.ToDictionary(a => a.Key, a => a.Value);
            }
        }
        private async Task<List<SettingValueCacheItem>> GetCacheItem(string groupKey, SettingScope settingScope, string settingScopeKey = null, CancellationToken cancellationToken = default)
        {
            var cacheKey = BuildCacheKey(groupKey, settingScope, settingScopeKey);
            return await _distributedCache.GetAsync<List<SettingValueCacheItem>>(cacheKey, cancellationToken);
        }
        private string BuildCacheKey(string groupKey, SettingScope settingScope, string settingScopeKey)
        {
            return $"{groupKey}:{settingScope}"+ (settingScope == SettingScope.Golbal ? "" : $":{settingScopeKey}");
        }
    }
}

using Wheel.Domain.Settings;
using Wheel.Enums;

namespace Wheel.Settings
{
    public class SettingValueCacheItem
    {
        public string Key { get; set; }
        public string Value { get; set; }
        public SettingValueType ValueType { get; set; }
    }
}

這裡獲取設定時優先從快取讀取,若快取沒有,則取資料庫,若資料庫再沒有,則從SettingDefintion中獲取預設值。
那麼這裡快取資料從哪裡來呢?細心的可以看到上面的SettingManager的修改設定的方法中有一行程式碼:

await _distributedEventBus.PublishAsync(new UpdateSettingEventData() { GroupName = settingGroupName, SettingScope = settingValues.First().SettingScope, SettingScopeKey = settingValues.First().SettingScopeKey });

這裡通過訊息佇列,通知更新快取。

UpdateSettingEvent

using Wheel.Enums;

namespace Wheel.EventBus.EventDatas
{
    [EventName("UpdateSetting")]
    public class UpdateSettingEventData
    {
        public string GroupName { get; set; }
        public SettingScope SettingScope { get; set; }
        public string? SettingScopeKey { get; set; }
    }
}
using AutoMapper;
using Microsoft.Extensions.Caching.Distributed;
using Wheel.DependencyInjection;
using Wheel.Domain.Settings;
using Wheel.EventBus.Distributed;
using Wheel.EventBus.EventDatas;
using Wheel.Services.SettingManage.Dtos;

namespace Wheel.EventBus.Handlers
{
    public class UpdateSettingEventHandler : IDistributedEventHandler<UpdateSettingEventData>, ITransientDependency
    {

        private readonly SettingManager _settingManager;
        private readonly IDistributedCache _distributedCache;
        private readonly IMapper _mapper;

        public UpdateSettingEventHandler(SettingManager settingManager, IDistributedCache distributedCache, IMapper mapper)
        {
            _settingManager = settingManager;
            _distributedCache = distributedCache;
            _mapper = mapper;
        }

        public async Task Handle(UpdateSettingEventData eventData, CancellationToken cancellationToken = default)
        {
            var settings = await _settingManager.GetSettingValues(eventData.GroupName, eventData.SettingScope, eventData.SettingScopeKey, cancellationToken);
            
            await _distributedCache.SetAsync($"Setting:{eventData.GroupName}:{eventData.SettingScope}" + (eventData.SettingScope == Enums.SettingScope.Golbal ? "" : $":{eventData.SettingScopeKey}"), _mapper.Map<List<SettingValueDto>>(settings));
        }
    }
}

UpdateSettingEventHandler負責在設定更新之後,獲取最新的設定直接塞到快取當中。
只需一行程式碼將SettingProvider加入到WheelServiceBase和WheelControllerBase中,後續就可以很方便的獲取設定,不需要頻繁在構造器注入:

public ISettingProvider SettingProvider => LazyGetService<ISettingProvider>();

測試

啟動程式,測試一下獲取設定值,這裡可以看到,我們通過SettingProvider成功讀取了設定。


就這樣,我們完成了我們的設定管理功能。

輪子倉庫地址https://github.com/Wheel-Framework/Wheel
歡迎進群催更。