0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HybridCache混合缓存

Posted at

asp.net core 9中、HyBridCacheが導入されました。これは本質的に全く新しい種類のキャッシュではなく、従来のキャッシュと組み合わせて使用されます。

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.0-preview.4.24267.6" />
  </ItemGroup>
</Project>

以下の例では、time0はメモリキャッシュ、time1はRedisに基づく分散キャッシュ、time3はハイブリッドキャッシュです。

もしtime0、time1がそれぞれ独立しているなら、time2はMemoryまたはDistributedキャッシュに基づいています。デフォルトでは、builder.Services.AddHybridCacheはメモリキャッシュに基づいていますが、他の分散キャッシュを基にしたい場合は、対応するServiceを追加するだけです。

using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.Caching.Memory;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMemoryCache();

builder.Services.AddStackExchangeRedisCache(opt =>
{
    opt.ConfigurationOptions = new StackExchange.Redis.ConfigurationOptions
    {
        EndPoints = { "localhost:6379" },
        AbortOnConnectFail = false
    };
});

builder.Services.AddHybridCache();

var app = builder.Build();

app.MapGet("/time0", async (IMemoryCache cache) =>
{
    return await cache.GetOrCreateAsync("time0", async _ => await Task.FromResult(DateTime.Now));
});

app.MapGet("/time1", async (IDistributedCache cache) =>
{
    var time = await cache.GetStringAsync("time1");
    if (string.IsNullOrWhiteSpace(time))
    {
        time = DateTime.Now.ToString();
        await cache.SetStringAsync("time1", time);
    }
    return time;
});

app.MapGet("/time2", async (HybridCache cache) =>
{
    return await cache.GetOrCreateAsync("time2", async _ => await Task.FromResult(DateTime.Now));
});

app.Run();

上記のコードによると、メモリーと一つの分散キャッシュが追加された場合、ハイブリッドキャッシュはどちらを使用するのか?実験してみて、結果をこの記事のコメントに同期してください。:)

(Translated by GPT)

元のリンク:https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247488177&idx=1&sn=cfd5676278779249afb56dba720c3352&chksm=9f004d9ba877c48d74f41af484b3dcb0f7a52c8f299f401dd12c4ac1d68421fc23a26f1c6520&token=1053798272&lang=zh_CN#rd&wt.mc_id=MVP_325642

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?