Add project files.

This commit is contained in:
Sergio Matias Urquin
2025-04-29 18:42:29 -06:00
parent 9c1958d351
commit 83fc1878c4
67 changed files with 4586 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.Blueprint.Redis
{
public interface ICacheSettings
{
int DefaultCacheDurationInMinutes { get; set; }
}
/// <summary>
/// Represents the settings for Redis caching.
/// </summary>
public class CacheSettings: ICacheSettings
{
/// <summary>
/// Gets or sets the default cache duration in minutes.
/// </summary>
public int DefaultCacheDurationInMinutes { get; set; }
}
}

View File

@@ -0,0 +1,43 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Core.Blueprint.Redis.Configuration
{
/// <summary>
/// Provides extension methods for registering Redis-related services in the DI container.
/// </summary>
public static class RegisterBlueprint
{
/// <summary>
/// Adds Redis caching services to the service collection.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
/// <param name="configuration">The application configuration object.</param>
/// <returns>The updated service collection.</returns>
public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
{
// Retrieve the Redis connection string from the configuration.
// Get Redis configuration section
var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value;
if (string.IsNullOrEmpty(redisConnectionString))
{
throw new InvalidOperationException("Redis connection is not configured.");
}
// Register RedisCacheProvider
services.AddSingleton<IRedisCacheProvider>(provider =>
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>()));
// Get CacheSettings and register with the ICacheSettings interface
var cacheSettings = configuration.GetSection("CacheSettings").Get<CacheSettings>();
if (cacheSettings == null)
{
throw new InvalidOperationException("Redis CacheSettings section is not configured.");
}
services.AddSingleton<ICacheSettings>(cacheSettings);
return services;
}
}
}

View File

@@ -0,0 +1,48 @@
namespace Core.Blueprint.Redis
{
/// <summary>
/// Interface for managing Redis cache operations.
/// </summary>
public interface IRedisCacheProvider
{
/// <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, or default if not found.</returns>
ValueTask<TEntity> GetAsync<TEntity>(string key);
/// <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>
/// <returns>A task representing the asynchronous operation.</returns>
ValueTask SetAsync<TEntity>(string key, TEntity value, TimeSpan? expiry = null);
/// <summary>
/// Removes a cache item by its key.
/// </summary>
/// <param name="key">The cache key.</param>
/// <returns>A task representing the asynchronous operation.</returns>
ValueTask RemoveAsync(string key);
/// <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>
ValueTask<bool> ExistsAsync(string key);
/// <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>
/// <returns>A task representing the asynchronous operation.</returns>
ValueTask RefreshAsync(string key, TimeSpan? expiry = null);
}
}

View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.StackExchangeRedis" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0" />
<PackageReference Include="StackExchange.Redis" Version="2.8.22" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Core.Blueprint.Redis.Helpers
{
/// <summary>
/// Helper class for generating consistent and normalized cache keys.
/// </summary>
public static class CacheKeyHelper
{
/// <summary>
/// Generates a cache key based on the instance, method name, and parameters.
/// </summary>
/// <param name="instance">The instance of the class.</param>
/// <param name="methodName">The method name related to the cache key.</param>
/// <param name="parameters">The parameters used to generate the key.</param>
/// <returns>A normalized cache key string.</returns>
public static string GenerateCacheKey(object instance, string methodName, params object[] parameters)
{
var className = instance.GetType().Name;
var keyBuilder = new StringBuilder($"{className}.{methodName}");
foreach (var param in parameters)
{
string normalizedParam = NormalizeParameter(param);
keyBuilder.Append($".{normalizedParam}");
}
return keyBuilder.ToString();
}
/// <summary>
/// Normalizes a parameter value for use in a cache key.
/// </summary>
/// <param name="param">The parameter to normalize.</param>
/// <returns>A normalized string representation of the parameter.</returns>
private static string NormalizeParameter(object param)
{
if (param == null)
{
return "null";
}
string paramString;
if (param is DateTime dateTime)
{
paramString = dateTime.ToString("yyyyMMdd");
}
else
{
paramString = param.ToString();
}
// Replace special characters with an underscore.
return Regex.Replace(paramString, @"[^a-zA-Z0-9]", "_");
}
}
}

View File

@@ -0,0 +1,171 @@
using Azure.Identity;
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;
/// <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;
}
}
}
}