97 lines
2.9 KiB
C#
97 lines
2.9 KiB
C#
using Microsoft.Extensions.Caching.Memory;
|
|
|
|
namespace DramaLing.Api.Services.Infrastructure.Caching;
|
|
|
|
public class MemoryCacheProvider : ICacheProvider
|
|
{
|
|
private readonly IMemoryCache _memoryCache;
|
|
private readonly ILogger<MemoryCacheProvider> _logger;
|
|
|
|
public string ProviderName => "Memory";
|
|
|
|
public MemoryCacheProvider(
|
|
IMemoryCache memoryCache,
|
|
ILogger<MemoryCacheProvider> logger)
|
|
{
|
|
_memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public Task<T?> GetAsync<T>(string key) where T : class
|
|
{
|
|
try
|
|
{
|
|
if (_memoryCache.TryGetValue(key, out T? result))
|
|
{
|
|
_logger.LogDebug("Memory cache hit for key: {Key}", key);
|
|
return Task.FromResult(result);
|
|
}
|
|
|
|
_logger.LogDebug("Memory cache miss for key: {Key}", key);
|
|
return Task.FromResult<T?>(null);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error getting from memory cache for key: {Key}", key);
|
|
return Task.FromResult<T?>(null);
|
|
}
|
|
}
|
|
|
|
public Task<bool> SetAsync<T>(string key, T value, TimeSpan expiry) where T : class
|
|
{
|
|
try
|
|
{
|
|
_memoryCache.Set(key, value, expiry);
|
|
_logger.LogDebug("Memory cache set for key: {Key}, expiry: {Expiry}", key, expiry);
|
|
return Task.FromResult(true);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error setting memory cache for key: {Key}", key);
|
|
return Task.FromResult(false);
|
|
}
|
|
}
|
|
|
|
public Task<bool> RemoveAsync(string key)
|
|
{
|
|
try
|
|
{
|
|
_memoryCache.Remove(key);
|
|
_logger.LogDebug("Memory cache removed for key: {Key}", key);
|
|
return Task.FromResult(true);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error removing from memory cache for key: {Key}", key);
|
|
return Task.FromResult(false);
|
|
}
|
|
}
|
|
|
|
public Task<bool> ExistsAsync(string key)
|
|
{
|
|
try
|
|
{
|
|
return Task.FromResult(_memoryCache.TryGetValue(key, out _));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error checking memory cache existence for key: {Key}", key);
|
|
return Task.FromResult(false);
|
|
}
|
|
}
|
|
|
|
public Task<bool> ClearAsync()
|
|
{
|
|
try
|
|
{
|
|
// MemoryCache 沒有直接清除所有項目的方法
|
|
_logger.LogWarning("Memory cache clear is not directly supported");
|
|
return Task.FromResult(true);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error clearing memory cache");
|
|
return Task.FromResult(false);
|
|
}
|
|
}
|
|
} |