Files
Core.BluePrint.Packages/Core.Blueprint.Redis/RedisCacheProvider.cs
Efrain Marin ffed92e85c feat: updated caching support
- feat: Added memory caching support
- feat: refactored dependency injection methods
2025-05-19 10:29:52 -06:00

173 lines
6.7 KiB
C#

using Azure.Identity;
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System.Text.Json;
namespace Core.Blueprint.Caching
{
/// <summary>
/// Redis cache provider for managing cache operations.
/// </summary>
public sealed class RedisCacheProvider : ICacheProvider
{
private IDatabase _cacheDatabase = null!;
private readonly ILogger<RedisCacheProvider> _logger;
/// <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)
{
if (string.IsNullOrWhiteSpace(connectionString))
throw new ArgumentNullException(nameof(connectionString), "Redis connection string cannot be null or empty.");
_logger = logger;
_cacheDatabase = InitializeRedisAsync(connectionString).GetAwaiter().GetResult();
}
/// <summary>
/// Initializes and establishes a connection to Redis using the provided connection string.
/// </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.</exce
async Task<IDatabase> InitializeRedisAsync(string connectionString)
{
try
{
var configurationOptions = await ConfigurationOptions.Parse($"{connectionString}")
.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
configurationOptions.AbortOnConnectFail = false;
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
_logger.LogInformation("Successfully connected to Redis.");
return connectionMultiplexer.GetDatabase();
}
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
{
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);
}
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
{
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
{
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
{
var exists = await _cacheDatabase.KeyExistsAsync(key);
_logger.LogInformation($"Cache item exists check for key: {key} - {exists}");
return exists;
}
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
{
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;
}
}
}
}