dramaling-vocab-learning/backend/DramaLing.Api/Services/Infrastructure/Caching/DistributedCacheProvider.cs

111 lines
3.5 KiB
C#

using Microsoft.Extensions.Caching.Distributed;
namespace DramaLing.Api.Services.Infrastructure.Caching;
public class DistributedCacheProvider : ICacheProvider
{
private readonly IDistributedCache _distributedCache;
private readonly ICacheSerializer _serializer;
private readonly ILogger<DistributedCacheProvider> _logger;
public string ProviderName => "Distributed";
public DistributedCacheProvider(
IDistributedCache distributedCache,
ICacheSerializer serializer,
ILogger<DistributedCacheProvider> logger)
{
_distributedCache = distributedCache ?? throw new ArgumentNullException(nameof(distributedCache));
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<T?> GetAsync<T>(string key) where T : class
{
try
{
var data = await _distributedCache.GetAsync(key);
if (data != null)
{
var result = _serializer.Deserialize<T>(data);
if (result != null)
{
_logger.LogDebug("Distributed cache hit for key: {Key}", key);
return result;
}
}
_logger.LogDebug("Distributed cache miss for key: {Key}", key);
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting from distributed cache for key: {Key}", key);
return null;
}
}
public async Task<bool> SetAsync<T>(string key, T value, TimeSpan expiry) where T : class
{
try
{
var data = _serializer.Serialize(value);
var options = new DistributedCacheEntryOptions
{
SlidingExpiration = expiry
};
await _distributedCache.SetAsync(key, data, options);
_logger.LogDebug("Distributed cache set for key: {Key}, expiry: {Expiry}", key, expiry);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error setting distributed cache for key: {Key}", key);
return false;
}
}
public async Task<bool> RemoveAsync(string key)
{
try
{
await _distributedCache.RemoveAsync(key);
_logger.LogDebug("Distributed cache removed for key: {Key}", key);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error removing from distributed cache for key: {Key}", key);
return false;
}
}
public async Task<bool> ExistsAsync(string key)
{
try
{
var data = await _distributedCache.GetAsync(key);
return data != null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error checking distributed cache existence for key: {Key}", key);
return false;
}
}
public Task<bool> ClearAsync()
{
try
{
_logger.LogWarning("Distributed cache clear implementation depends on the provider");
return Task.FromResult(true);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error clearing distributed cache");
return Task.FromResult(false);
}
}
}