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是自己当家做主的话,那么tim2就要基于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();
如上代码,如果添加了内存,和一种分布式,那么混合缓存用的是谁呢?请自行试验,可以把结果同步到本篇文章的评论里。:)