50 lines
2.0 KiB
C#
50 lines
2.0 KiB
C#
using System.Text.Json;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
using Microsoft.Extensions.Options;
|
|
using TakeoutSaaS.Application.Dictionary.Abstractions;
|
|
using TakeoutSaaS.Application.Dictionary.Models;
|
|
using TakeoutSaaS.Infrastructure.Dictionary.Options;
|
|
|
|
namespace TakeoutSaaS.Infrastructure.Dictionary.Services;
|
|
|
|
/// <summary>
|
|
/// 基于 IDistributedCache 的字典缓存实现。
|
|
/// </summary>
|
|
public sealed class DistributedDictionaryCache(IDistributedCache cache, IOptions<DictionaryCacheOptions> options) : IDictionaryCache
|
|
{
|
|
private readonly DictionaryCacheOptions _options = options.Value;
|
|
private readonly JsonSerializerOptions _serializerOptions = new(JsonSerializerDefaults.Web);
|
|
|
|
public async Task<IReadOnlyList<DictionaryItemDto>?> GetAsync(long tenantId, string code, CancellationToken cancellationToken = default)
|
|
{
|
|
var cacheKey = BuildKey(tenantId, code);
|
|
var payload = await cache.GetAsync(cacheKey, cancellationToken);
|
|
if (payload == null || payload.Length == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return JsonSerializer.Deserialize<List<DictionaryItemDto>>(payload, _serializerOptions);
|
|
}
|
|
|
|
public Task SetAsync(long tenantId, string code, IReadOnlyList<DictionaryItemDto> items, CancellationToken cancellationToken = default)
|
|
{
|
|
var cacheKey = BuildKey(tenantId, code);
|
|
var payload = JsonSerializer.SerializeToUtf8Bytes(items, _serializerOptions);
|
|
var options = new DistributedCacheEntryOptions
|
|
{
|
|
SlidingExpiration = _options.SlidingExpiration
|
|
};
|
|
return cache.SetAsync(cacheKey, payload, options, cancellationToken);
|
|
}
|
|
|
|
public Task RemoveAsync(long tenantId, string code, CancellationToken cancellationToken = default)
|
|
{
|
|
var cacheKey = BuildKey(tenantId, code);
|
|
return cache.RemoveAsync(cacheKey, cancellationToken);
|
|
}
|
|
|
|
private static string BuildKey(long tenantId, string code)
|
|
=> $"dictionary:{tenantId}:{code.ToLowerInvariant()}";
|
|
}
|