ResilientRedis.Client
1.0.0
There is a newer version of this package available.
See the version list below for details.
See the version list below for details.
dotnet add package ResilientRedis.Client --version 1.0.0
NuGet\Install-Package ResilientRedis.Client -Version 1.0.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ResilientRedis.Client" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ResilientRedis.Client" Version="1.0.0" />
<PackageReference Include="ResilientRedis.Client" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ResilientRedis.Client --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: ResilientRedis.Client, 1.0.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ResilientRedis.Client@1.0.0
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ResilientRedis.Client&version=1.0.0
#tool nuget:?package=ResilientRedis.Client&version=1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Resilient Redis Client
Un cliente resiliente para Azure Cache for Redis con soporte para Managed Identity, Service Bus events y patrones de fallback.
Características
- ✅ Resiliencia: Reintentos automáticos con backoff exponencial
- ✅ Managed Identity: Autenticación segura sin connection strings
- ✅ Service Bus Integration: Publicación automática de eventos
- ✅ Fallback Service: Sistema de respaldo cuando Redis no está disponible
- ✅ Logging: Logging estructurado con diferentes niveles
- ✅ Métricas: Seguimiento de rendimiento y eventos
- ✅ Configuración flexible: Múltiples formas de configuración
Instalación
dotnet add package ResilientRedis.Client
Configuración
appsettings.json
{
"Redis": {
"HostName": "your-redis-cache.redis.cache.windows.net",
"Port": 6380,
"UseSsl": true,
"UseManagedIdentity": true,
"DefaultExpirationMinutes": 60,
"KeyPrefix": "myapp",
"MaxRetryAttempts": 3,
"RetryDelaySeconds": 2
},
"ServiceBus": {
"Namespace": "your-servicebus-namespace",
"RedisEventsTopic": "redis-events",
"UseManagedIdentity": true,
"EnableEventPublishing": true
},
"FallbackService": {
"BaseUrl": "https://your-api.azurewebsites.net",
"TimeoutSeconds": 30,
"MaxRetryAttempts": 2,
"Headers": {
"X-API-Key": "your-api-key"
}
}
}
Startup.cs / Program.cs
using Azure.Redis.Resilient.Client.Extensions;
// Configuración desde appsettings.json
builder.Services.AddResilientRedis(builder.Configuration);
// O configuración programática
builder.Services.AddResilientRedis(redis =>
{
redis.HostName = "your-redis-cache.redis.cache.windows.net";
redis.UseManagedIdentity = true;
redis.KeyPrefix = "myapp";
}, serviceBus =>
{
serviceBus.Namespace = "your-servicebus-namespace";
serviceBus.EnableEventPublishing = true;
});
Uso Básico
public class UserService
{
private readonly IResilientRedisClient _redisClient;
public UserService(IResilientRedisClient redisClient)
{
_redisClient = redisClient;
}
public async Task<User?> GetUserAsync(int userId)
{
var key = $"user:{userId}";
// Obtener con fallback automático
var result = await _redisClient.GetOrCreateAsync(key, async () =>
{
// Este método se ejecuta solo si no está en cache
return await _userRepository.GetByIdAsync(userId);
}, TimeSpan.FromMinutes(30));
return result.Value;
}
public async Task<bool> CacheUserAsync(User user)
{
var key = $"user:{user.Id}";
var result = await _redisClient.SetAsync(key, user, TimeSpan.FromHours(1));
return result.Success;
}
}
Uso Avanzado
Operaciones con Resultados Detallados
public async Task<ApiResponse<User>> GetUserWithMetricsAsync(int userId)
{
var key = $"user:{userId}";
var result = await _redisClient.GetAsync<User>(key);
return new ApiResponse<User>
{
Data = result.Value,
FromCache = result.FromCache,
FromFallback = result.FromFallback,
ExecutionTime = result.ExecutionTime,
Success = result.Success
};
}
Invalidación por Patrón
public async Task InvalidateUserCacheAsync(int userId)
{
// Invalida todas las claves que coincidan con el patrón
var result = await _redisClient.InvalidatePatternAsync($"user:{userId}:*");
_logger.LogInformation("Invalidated {Count} cache entries", result.Value);
}
Eventos de Service Bus
El cliente publica automáticamente eventos a Service Bus que puedes consumir:
public class RedisEventHandler
{
public async Task HandleRedisEvent(RedisEvent redisEvent)
{
switch (redisEvent.EventType)
{
case RedisEventType.CacheMiss:
// Lógica para cache miss
break;
case RedisEventType.FallbackTriggered:
// Lógica para cuando se usa fallback
break;
case RedisEventType.Error:
// Lógica para errores
break;
}
}
}
Configuración de Managed Identity
En Azure App Service
- Habilita System Assigned Identity en tu App Service
- Asigna el rol "Redis Cache Contributor" a la identidad
- Configura
UseManagedIdentity: true
En desarrollo local
az login
# El cliente usará automáticamente tus credenciales de Azure CLI
Mejores Prácticas
- Prefijos de Claves: Usa prefijos consistentes para organizar tus datos
- Expiración: Siempre establece tiempos de expiración apropiados
- Fallback: Implementa servicios de fallback robustos
- Monitoring: Monitorea los eventos de Service Bus para detectar problemas
- Testing: Usa el patrón de inyección de dependencias para testing
Troubleshooting
Problemas de Conexión
- Verifica que Managed Identity esté habilitada
- Confirma que los roles de Azure estén asignados correctamente
- Revisa los logs para errores de autenticación
Problemas de Rendimiento
- Ajusta los valores de timeout y retry
- Monitorea las métricas de Service Bus
- Considera usar connection pooling
Contribuir
- Fork el repositorio
- Crea una rama para tu feature
- Commit tus cambios
- Push a la rama
- Crea un Pull Request
Licencia
MIT License - ver LICENSE para detalles.
Hecho con amor por ju4r3v0l para mis amigos y la comunidad de desarrolladores. ❤️
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- Azure.Identity (>= 1.12.1)
- Azure.Messaging.ServiceBus (>= 7.17.5)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Hosting (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.2)
- Polly (>= 8.2.0)
- StackExchange.Redis (>= 2.7.33)
- System.Text.Json (>= 8.0.5)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
v1.0.0:
- Initial release with resilient Redis client
- Azure Managed Identity support
- Service Bus event publishing
- Automatic fallback system
- Comprehensive logging and metrics
- Flexible configuration options