ResilientRedis.Client 1.0.0

There is a newer version of this package available.
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" />
                    
Directory.Packages.props
<PackageReference Include="ResilientRedis.Client" />
                    
Project file
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
                    
#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
                    
Install as a Cake Addin
#tool nuget:?package=ResilientRedis.Client&version=1.0.0
                    
Install as a Cake Tool

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

  1. Habilita System Assigned Identity en tu App Service
  2. Asigna el rol "Redis Cache Contributor" a la identidad
  3. Configura UseManagedIdentity: true

En desarrollo local

az login
# El cliente usará automáticamente tus credenciales de Azure CLI

Mejores Prácticas

  1. Prefijos de Claves: Usa prefijos consistentes para organizar tus datos
  2. Expiración: Siempre establece tiempos de expiración apropiados
  3. Fallback: Implementa servicios de fallback robustos
  4. Monitoring: Monitorea los eventos de Service Bus para detectar problemas
  5. 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

  1. Fork el repositorio
  2. Crea una rama para tu feature
  3. Commit tus cambios
  4. Push a la rama
  5. 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 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.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 180 7/2/2025
1.0.0 134 7/2/2025

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