Skip to content

Commit 5b44a12

Browse files
Merge pull request #10 from ferronicardoso/main
Create 2025-05-01-cache-distribuido-com-litedb.md
2 parents 731fba6 + b28e67b commit 5b44a12

1 file changed

Lines changed: 129 additions & 0 deletions

File tree

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
---
2+
title: 'Cache distribuído local com LiteDB e IDistributedCache no .NET'
3+
date: Thu, 01 May 2025 19:00:00 +0000
4+
draft: false
5+
tags: ['CSharp', 'C#', 'NET 9', 'NET 8', 'CSharpBrasil.Extensions.Caching.LiteDb', 'Caching', 'LiteDb', 'NoSql', 'IDistributedCache']
6+
---
7+
8+
## Introdução
9+
10+
O `IDistributedCache` é uma interface poderosa da plataforma .NET que permite abstrair o uso de cache distribuído em aplicações web, APIs e serviços. As implementações mais comuns incluem Redis ou SQL Server, mas e quando queremos algo mais leve, local e com persistência?
11+
12+
Neste artigo, apresento a biblioteca **CSharpBrasil.Extensions.Caching.LiteDb**, uma solução desenvolvida para oferecer caching distribuído local com o banco LiteDB — um banco NoSQL leve e embutido em C#.
13+
14+
## Por que usar LiteDB como backend de cache?
15+
16+
- **Sem dependências externas:** ideal para aplicações em containers, APIs internas e soluções desktop.
17+
- **Desempenho local otimizado:** armazena os dados em um único arquivo `.db`, com leitura simultânea e escrita isolada por coleção.
18+
- **Controle completo:** opções de segurança, rebuild, collation e cache cleanup automático.
19+
20+
## Instalação
21+
22+
Instale via NuGet:
23+
24+
```bash
25+
dotnet add package CSharpBrasil.Extensions.Caching.LiteDb
26+
```
27+
28+
## Configuração da biblioteca
29+
30+
A biblioteca implementa `IDistributedCache` e pode ser injetada com facilidade em qualquer aplicação .NET via `IServiceCollection`:
31+
32+
```csharp
33+
builder.Services.AddLiteDbDistributedCache(options =>
34+
{
35+
options.DatabasePath = "cache.db";
36+
options.CollectionName = "cache";
37+
options.Password = "sua-senha-opcional";
38+
options.CleanupInterval = TimeSpan.FromMinutes(10);
39+
options.EnableAutoCleanup = true;
40+
});
41+
```
42+
43+
### Opções disponíveis
44+
45+
```csharp
46+
public class LiteDbDistributedCacheOptions
47+
{
48+
public string DatabasePath { get; set; } = "cache.db";
49+
public string CollectionName { get; set; } = "cache";
50+
public bool EnableAutoCleanup { get; set; } = true;
51+
public TimeSpan CleanupInterval { get; set; } = TimeSpan.FromMinutes(10);
52+
public bool ReadOnly { get; set; } = false;
53+
public string? Password { get; set; }
54+
public bool Upgrade { get; set; } = false;
55+
public bool AutoRebuild { get; set; } = false;
56+
public long InitialSize { get; set; } = 0;
57+
public Collation Collation { get; set; } = Collation.Default;
58+
}
59+
```
60+
61+
## Exemplo de uso em API
62+
63+
```csharp
64+
[ApiController]
65+
[Route("api/cache")]
66+
public class CacheController : ControllerBase
67+
{
68+
private readonly IDistributedCache _cache;
69+
70+
public CacheController(IDistributedCache cache)
71+
{
72+
_cache = cache;
73+
}
74+
75+
[HttpPost("{key}")]
76+
public async Task<IActionResult> Set(string key, [FromBody] string value)
77+
{
78+
await _cache.SetStringAsync(key, value, new DistributedCacheEntryOptions
79+
{
80+
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
81+
});
82+
return Ok();
83+
}
84+
85+
[HttpGet("{key}")]
86+
public async Task<IActionResult> Get(string key)
87+
{
88+
var value = await _cache.GetStringAsync(key);
89+
return Ok(value ?? "(not found)");
90+
}
91+
}
92+
```
93+
94+
## Exemplo de uso em Console App
95+
96+
```csharp
97+
var host = Host.CreateDefaultBuilder(args)
98+
.ConfigureServices(services =>
99+
{
100+
services.AddLiteDbDistributedCache(options =>
101+
{
102+
options.DatabasePath = "console-cache.db";
103+
});
104+
})
105+
.Build();
106+
107+
var cache = host.Services.GetRequiredService<IDistributedCache>();
108+
109+
await cache.SetStringAsync("message", "Olá mundo!", new DistributedCacheEntryOptions
110+
{
111+
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(30)
112+
});
113+
114+
var result = await cache.GetStringAsync("message");
115+
Console.WriteLine($"Mensagem em cache: {result}");
116+
```
117+
118+
## Considerações finais
119+
120+
Essa biblioteca foi pensada para aplicações reais que precisam de caching local performático, com segurança e controle total sobre a persistência dos dados. O LiteDB é uma excelente alternativa quando não se quer depender de um Redis ou infraestrutura externa.
121+
122+
Acesse o código no GitHub e instale o pacote no NuGet para começar a usar agora mesmo!
123+
124+
- **NuGet:** [CSharpBrasil.Extensions.Caching.LiteDb](https://www.nuget.org/packages/CSharpBrasil.Extensions.Caching.LiteDb)
125+
- **GitHub:** https://github.com/csharpbrasil/CSharpBrasil.Extensions.Caching.LiteDb
126+
127+
Participe da nossa comunidade no [WhastApp](https://chat.whatsapp.com/CYW7HUiK70xAmPpFx9mVMR).
128+
129+
Bons estudos e mãos à obra!

0 commit comments

Comments
 (0)