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;
///
/// 基于 IDistributedCache 的字典缓存实现。
///
public sealed class DistributedDictionaryCache(IDistributedCache cache, IOptions options) : IDictionaryCache
{
private readonly DictionaryCacheOptions _options = options.Value;
private readonly JsonSerializerOptions _serializerOptions = new(JsonSerializerDefaults.Web);
public async Task?> 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>(payload, _serializerOptions);
}
public Task SetAsync(long tenantId, string code, IReadOnlyList 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()}";
}