From bfd1ee05473b1205038a4069c091039ead735d46 Mon Sep 17 00:00:00 2001 From: hello Date: Tue, 25 Mar 2025 14:43:13 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BC=95=E5=85=A5=E6=B7=B7=E5=90=88=E7=BC=93?= =?UTF-8?q?=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/helloshop/diagrams/hybridcache.drawio | 25 +++++++ notes/helloshop/hybrid-cache-library.md | 82 +++++++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 notes/helloshop/diagrams/hybridcache.drawio create mode 100644 notes/helloshop/hybrid-cache-library.md diff --git a/notes/helloshop/diagrams/hybridcache.drawio b/notes/helloshop/diagrams/hybridcache.drawio new file mode 100644 index 0000000..72c9309 --- /dev/null +++ b/notes/helloshop/diagrams/hybridcache.drawio @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/notes/helloshop/hybrid-cache-library.md b/notes/helloshop/hybrid-cache-library.md new file mode 100644 index 0000000..4a168de --- /dev/null +++ b/notes/helloshop/hybrid-cache-library.md @@ -0,0 +1,82 @@ +# 使用 HybridCache 混合缓存库 + +混合缓存可以同时使用内存缓存和分布式缓存,它可以提高缓存的命中率,减少对分布式缓存的访问,从而提高性能。 + +- 当从缓存中获取数据时,它首先会从内存缓存中获取数据,如果内存缓存中没有数据,它会从分布式缓存中获取数据。 +- 当向缓存中写入数据时,它会同时向内存缓存和分布式缓存中写入数据。 + +```text + +Service 1 ----> HybridCache ----> MemoryCache ----> DistributedCache + +``` + + +## 安装程序包 + +```shell +dotnet add package Microsoft.Extensions.Caching.Hybrid +``` + +## 配置服务 + +```csharp +builder.Services.AddHybridCache(); +``` + +## 使用服务 + +```csharp +public class SomeService(HybridCache cache) +{ + private HybridCache _cache = cache; + + public async Task GetSomeInfoAsync(string name, int id, CancellationToken token = default) + { + return await _cache.GetOrCreateAsync( $"{name}-{id}",async cancel => await GetDataFromTheSourceAsync(name, id, cancel),cancellationToken: token ); + } + + public async Task GetDataFromTheSourceAsync(string name, int id, CancellationToken token) + { + string someInfo = $"someinfo-{name}-{id}"; + return someInfo; + } +} +``` + +## 按标记移除缓存条目 + +```csharp +public class SomeService(HybridCache cache) +{ + private HybridCache _cache = cache; + + public async Task GetSomeInfoAsync(string name, int id, CancellationToken token = default) + { + var tags = new List { "tag1", "tag2", "tag3" }; + var entryOptions = new HybridCacheEntryOptions + { + Expiration = TimeSpan.FromMinutes(1), + LocalCacheExpiration = TimeSpan.FromMinutes(1) + }; + return await _cache.GetOrCreateAsync( + $"{name}-{id}", // Unique key to the cache entry + async cancel => await GetDataFromTheSourceAsync(name, id, cancel), + entryOptions, + tags, + cancellationToken: token + ); + } + + public async Task GetDataFromTheSourceAsync(string name, int id, CancellationToken token) + { + string someInfo = $"someinfo-{name}-{id}"; + return someInfo; + } + + public async Task RemoveByTagAsync(string tag) + { + await _cache.RemoveByTagAsync(tag); + } +} +``` \ No newline at end of file