RetailSolutions.Shared.Cache 1.2.89

There is a newer version of this package available.
See the version list below for details.
dotnet add package RetailSolutions.Shared.Cache --version 1.2.89
                    
NuGet\Install-Package RetailSolutions.Shared.Cache -Version 1.2.89
                    
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="RetailSolutions.Shared.Cache" Version="1.2.89" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RetailSolutions.Shared.Cache" Version="1.2.89" />
                    
Directory.Packages.props
<PackageReference Include="RetailSolutions.Shared.Cache" />
                    
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 RetailSolutions.Shared.Cache --version 1.2.89
                    
#r "nuget: RetailSolutions.Shared.Cache, 1.2.89"
                    
#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 RetailSolutions.Shared.Cache@1.2.89
                    
#: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=RetailSolutions.Shared.Cache&version=1.2.89
                    
Install as a Cake Addin
#tool nuget:?package=RetailSolutions.Shared.Cache&version=1.2.89
                    
Install as a Cake Tool

RetailSolutions.Shared.Cache

Biblioteca de abstrações para cache com suporte a Redis e Memory Cache, incluindo distributed locks usando RedLock.net.

Instalação

dotnet add package RetailSolutions.Shared.Cache

Ou via Package Manager Console:

Install-Package RetailSolutions.Shared.Cache

Uso

Configuração de Cache

Registre os serviços de cache no seu IServiceCollection:

using RetailSolutions.Shared.Cache;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCache(builder.Configuration);

Configuração no appsettings.json

Configure o cache no appsettings.json:

{
  "Cache": {
    "Type": "redis",
    "Redis": {
      "ConnectionString": "localhost:6379"
    }
  }
}

Para usar Memory Cache:

{
  "Cache": {
    "Type": "memory"
  }
}

Para ambientes de produção com Redis:

{
  "Cache": {
    "Type": "redis",
    "Redis": {
      "ConnectionString": "servidor:6379,password=senha,ssl=true,abortConnect=false"
    }
  }
}

Detecção Automática de Ambiente

O método AddCache detecta automaticamente o ambiente e escolhe o tipo de cache apropriado:

  • Kubernetes: Se detectado e Redis estiver disponível, usa Redis
  • IIS: Usa Memory Cache por padrão
  • Outros: Usa Memory Cache como padrão

Serviços Registrados

O método AddCache registra automaticamente:

  • ICacheService (scoped) - Serviço de cache (Redis ou Memory)
  • IConnectionMultiplexer (singleton) - Conexão com Redis (quando usando Redis)
  • CacheServiceFactory (scoped) - Factory para criar serviços de cache

Validação de Conexão Redis

Para garantir que a conexão Redis está funcionando antes da aplicação iniciar, use o método UseCache:

using RetailSolutions.Shared.Cache;

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services => {
        services.AddCache(configuration);
    })
    .Build()
    .UseCache(); // Valida a conexão Redis antes de iniciar

await host.RunAsync();

Para aplicações ASP.NET Core:

using RetailSolutions.Shared.Cache;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCache(builder.Configuration);

var app = builder.Build();

// Valida a conexão Redis antes de iniciar a aplicação
var host = app.Services.GetRequiredService<IHost>();
host.UseCache();

// ... configure middleware ...

app.Run();

O método UseCache:

  • ✅ Valida se a conexão Redis está estabelecida
  • ✅ Executa um health check (write/read/delete) para garantir que Redis está funcionando
  • ✅ Lança uma exceção se a validação falhar, impedindo a inicialização da aplicação
  • ✅ Ignora a validação se o tipo de cache não for Redis (Memory Cache)
  • ✅ Registra logs informativos sobre o status da validação

Configuração de Distributed Locks

Para usar distributed locks com RedLock.net:

using RetailSolutions.Shared.Cache;

var builder = Host.CreateApplicationBuilder(args);

var redisConnectionString = builder.Configuration.GetConnectionString("Redis");
builder.AddRedisLock(redisConnectionString, "NomeDaSuaAplicacao");

O método AddRedisLock registra:

  • IDistributedLockFactory (singleton) - Factory para criar distributed locks
  • IConnectionMultiplexer (scoped) - Conexão direta com Redis

Exemplo: Usando Cache Service

using RetailSolutions.Shared.Cache;

public class ProdutoService
{
    private readonly ICacheService _cache;

    public ProdutoService(ICacheService cache)
    {
        _cache = cache;
    }

    public async Task<Produto> ObterProdutoAsync(string id)
    {
        var cacheKey = $"produto:{id}";
        
        return await _cache.GetOrSetAsync(cacheKey, async () => {
            // Busca do banco de dados se não estiver em cache
            return await _repository.ObterPorIdAsync(id);
        }, TimeSpan.FromMinutes(30));
    }

    public async Task InvalidarCacheAsync(string id)
    {
        var cacheKey = $"produto:{id}";
        await _cache.RemoveAsync(cacheKey);
  }
}

Exemplo: Usando Distributed Lock

using RedLockNet;

public class ProcessamentoService
{
    private readonly IDistributedLockFactory _lockFactory;

    public ProcessamentoService(IDistributedLockFactory lockFactory)
    {
        _lockFactory = lockFactory;
    }

    public async Task ProcessarRecursoCompartilhado()
    {
        var resource = "recurso-compartilhado";
        var expiryTime = TimeSpan.FromSeconds(30);

        await using var redLock = await _lockFactory.CreateLockAsync(
            resource, 
            expiryTime
        );

        if (redLock.IsAcquired)
        {
            // Lógica crítica executada com lock distribuído
            await ProcessarDados();
        }
        else
        {
            // Lock não adquirido, outro processo está usando o recurso
            throw new InvalidOperationException("Recurso está sendo usado por outro processo");
        }
    }

    private Task ProcessarDados() => Task.CompletedTask;
}

Exemplo: Acesso Direto ao Redis

using StackExchange.Redis;

public class CacheService
{
    private readonly IConnectionMultiplexer _redis;

    public CacheService(IConnectionMultiplexer redis)
    {
        _redis = redis;
    }

    public async Task<string?> ObterValorAsync(string chave)
    {
        var db = _redis.GetDatabase();
        var valor = await db.StringGetAsync(chave);
        return valor.ToString();
    }

    public async Task DefinirValorAsync(string chave, string valor, TimeSpan? expiracao = null)
    {
        var db = _redis.GetDatabase();
        await db.StringSetAsync(chave, valor, expiracao);
    }
}

Dependências

  • Microsoft.Extensions.Configuration (10.0.1)
  • Microsoft.Extensions.DependencyInjection (10.0.1)
  • Microsoft.Extensions.Hosting (10.0.1)
  • Microsoft.Extensions.Caching.Memory (10.0.1)
  • RedLock.net (2.3.2)
  • StackExchange.Redis (2.9.25)
  • Serilog (para logging)

Requisitos

  • .NET 10.0 ou superior
  • Instância Redis disponível (opcional, se usar Memory Cache não é necessário)

Features

  • ✅ Suporte a Redis Cache
  • ✅ Suporte a Memory Cache
  • ✅ Detecção automática de ambiente (Kubernetes, IIS)
  • ✅ Fallback automático para Memory Cache se Redis falhar
  • ✅ Validação de conexão Redis na inicialização (UseCache)
  • ✅ Distributed Locks com RedLock.net
  • ✅ Configuração via appsettings.json
  • ✅ Factory pattern para criação de serviços de cache

Tags

Gemco, RetailSolutions, Redis, Cache, MemoryCache, DistributedLock, RedLock

Licença

Copyright © Retail Solutions

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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 (3)

Showing the top 3 NuGet packages that depend on RetailSolutions.Shared.Cache:

Package Downloads
RetailSolutions.Shared.Jobs

Controle de execução de cronjobs

RetailSolutions.Shared.Max

Abstrações da Max Sistemas

RetailSolutions.Shared.Ifood

Abstrações do Ifood

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.1400 159 7/7/2026
1.3.1370 109 7/6/2026
1.2.122 127 7/6/2026
1.2.107 104 4/30/2026
1.2.90 682 12/13/2025
1.2.89 199 12/13/2025
1.2.84 196 12/13/2025
1.2.73 250 12/12/2025
1.2.70 154 12/12/2025