211 lines
8.0 KiB
C#
211 lines
8.0 KiB
C#
using Azure.Identity;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Logging;
|
|
using StackExchange.Redis;
|
|
using System.Text.Json;
|
|
|
|
namespace Core.Blueprint.Redis
|
|
{
|
|
/// <summary>
|
|
/// Redis cache provider for managing cache operations.
|
|
/// </summary>
|
|
public sealed class RedisCacheProvider : IRedisCacheProvider
|
|
{
|
|
private IDatabase _cacheDatabase = null!;
|
|
private readonly ILogger<RedisCacheProvider> _logger;
|
|
private readonly bool _useRedis;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="RedisCacheProvider"/> class.
|
|
/// </summary>
|
|
/// <param name="connectionString">The Redis connection string.</param>
|
|
/// <param name="logger">The logger instance for logging operations.</param>
|
|
/// <exception cref="ArgumentNullException">Thrown when connection string is null or empty.</exception>
|
|
public RedisCacheProvider(string connectionString, ILogger<RedisCacheProvider> logger, IConfiguration configuration)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(connectionString))
|
|
throw new ArgumentNullException(nameof(connectionString), "Redis connection string cannot be null or empty.");
|
|
|
|
_logger = logger;
|
|
_useRedis = configuration.GetValue<bool>("UseRedisCache", false);
|
|
_cacheDatabase = InitializeRedisAsync(connectionString).GetAwaiter().GetResult();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initializes and establishes a connection to Redis based on the environment.
|
|
/// Uses a local connection in development, and Azure with token credentials in other environments.
|
|
/// </summary>
|
|
/// <param name="connectionString">The Redis connection string.</param>
|
|
/// <returns>An <see cref="IDatabase"/> instance representing the Redis cache database.</returns>
|
|
/// <exception cref="Exception">Thrown when the connection to Redis fails.</exception>
|
|
async Task<IDatabase?> InitializeRedisAsync(string connectionString)
|
|
{
|
|
try
|
|
{
|
|
if (_useRedis)
|
|
{
|
|
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
|
|
ConnectionMultiplexer connectionMultiplexer;
|
|
|
|
if (environment.Equals("Local", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(connectionString);
|
|
}
|
|
else
|
|
{
|
|
var configurationOptions = await ConfigurationOptions.Parse(connectionString)
|
|
.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
|
|
|
|
configurationOptions.AbortOnConnectFail = false;
|
|
|
|
connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
|
|
}
|
|
|
|
_logger.LogInformation("Successfully connected to Redis.");
|
|
|
|
return connectionMultiplexer.GetDatabase();
|
|
}
|
|
|
|
return null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error establishing Redis connection.");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Retrieves a cache item by its key.
|
|
/// </summary>
|
|
/// <typeparam name="T">The type of the cached item.</typeparam>
|
|
/// <param name="key">The cache key.</param>
|
|
/// <returns>The cached item of type <typeparamref name="T"/>, or default if not found.</returns>
|
|
public async ValueTask<TEntity> GetAsync<TEntity>(string key)
|
|
{
|
|
try
|
|
{
|
|
if (_useRedis is not false)
|
|
{
|
|
var value = await _cacheDatabase.StringGetAsync(key);
|
|
|
|
if (value.IsNullOrEmpty)
|
|
{
|
|
_logger.LogInformation($"Cache miss for key: {key}");
|
|
return default;
|
|
}
|
|
|
|
_logger.LogInformation($"Cache hit for key: {key}");
|
|
return JsonSerializer.Deserialize<TEntity>(value);
|
|
}
|
|
|
|
return default;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, $"Error getting cache item with key {key}");
|
|
throw;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Sets a cache item with the specified key and value.
|
|
/// </summary>
|
|
/// <typeparam name="T">The type of the item to cache.</typeparam>
|
|
/// <param name="key">The cache key.</param>
|
|
/// <param name="value">The item to cache.</param>
|
|
/// <param name="expiry">The optional expiration time for the cache item.</param>
|
|
public async ValueTask SetAsync<TEntity>(string key, TEntity value, TimeSpan? expiry = null)
|
|
{
|
|
try
|
|
{
|
|
if (_useRedis is not false)
|
|
{
|
|
var json = JsonSerializer.Serialize(value);
|
|
await _cacheDatabase.StringSetAsync(key, json, expiry);
|
|
_logger.LogInformation($"Cache item set with key: {key}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, $"Error setting cache item with key {key}");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Removes a cache item by its key.
|
|
/// </summary>
|
|
/// <param name="key">The cache key.</param>
|
|
public async ValueTask RemoveAsync(string key)
|
|
{
|
|
try
|
|
{
|
|
if (_useRedis is not false)
|
|
{
|
|
await _cacheDatabase.KeyDeleteAsync(key);
|
|
_logger.LogInformation($"Cache item removed with key: {key}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, $"Error removing cache item with key {key}");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if a cache item exists for the specified key.
|
|
/// </summary>
|
|
/// <param name="key">The cache key.</param>
|
|
/// <returns>True if the cache item exists; otherwise, false.</returns>
|
|
public async ValueTask<bool> ExistsAsync(string key)
|
|
{
|
|
try
|
|
{
|
|
if (_useRedis is not false)
|
|
{
|
|
var exists = await _cacheDatabase.KeyExistsAsync(key);
|
|
_logger.LogInformation($"Cache item exists check for key: {key} - {exists}");
|
|
}
|
|
|
|
return false;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, $"Error checking existence of cache item with key {key}");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Refreshes the expiration time of a cache item if it exists.
|
|
/// </summary>
|
|
/// <param name="key">The cache key.</param>
|
|
/// <param name="expiry">The new expiration time for the cache item.</param>
|
|
public async ValueTask RefreshAsync(string key, TimeSpan? expiry = null)
|
|
{
|
|
try
|
|
{
|
|
if (_useRedis is not false)
|
|
{
|
|
var value = await _cacheDatabase.StringGetAsync(key);
|
|
if (!value.IsNullOrEmpty)
|
|
{
|
|
await _cacheDatabase.StringSetAsync(key, value, expiry);
|
|
_logger.LogInformation($"Cache item refreshed with key: {key}");
|
|
}
|
|
else
|
|
{
|
|
_logger.LogWarning($"Cache item with key: {key} does not exist, cannot refresh");
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, $"Error refreshing cache item with key {key}");
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|