gpt4 book ai didi

caching - IDistributedCache 的多个实例?

转载 作者:行者123 更新时间:2023-12-04 01:55:43 26 4
gpt4 key购买 nike

IDistributedCache作为标准 API 提供,用于从 ASP.NET 应用程序中访问分布式缓存。提供的 API 非常简单,基本上将缓存呈现为键值对的容器,DistributedCacheEntryOptions提供每次入场的到期选项。

现在假设在一个应用程序中有许多不同类型的数据需要缓存,其中一些我们可能希望在逻辑上进行分组。也许我们希望对某些类型的数据进行分组,以便我们可以例如选择从缓存中全部刷新而不影响其他类型的数据,或者我们希望能够将某些类型的数据放在具有高可用性的不同缓存集群中,或者更多资源以获得更好的性能等。

鉴于此,我倾向于拥有一个包含多个 IDistributedCache 实例的包含对象,每个实例用于逻辑分组。鉴于这似乎是一个常见的要求,我想知道是否有一些标准的方法可以实现这种模式。或者建议将所有内容放入一个带有复合键(例如 groupName-key)的缓存中,尽管我不希望这样做,因为我认为这会限制缓存层的灵 active 。

顺便说一句,我注意到 NCache API 提供了为每个缓存条目选择分配 groupName 和 subGroupName 的能力,我认为这正是我想要的。但是,我更愿意针对 IDistributedCache (或类似的)进行编码,以允许插入式替代缓存实现。

也许另一种选择是创建我自己的接口(interface)来提供抽象,但是我没有选择使用预先构建的现成 IDistributedCache 实现(例如来自 NCache 和 Redis)。

另见:https://github.com/aspnet/Extensions/issues/2802

最佳答案

... within a single app there are lots of different types of data to be cached, some of which we may wish to logically group.



您可以使用如下包装器接口(interface)对缓存进行分组:
public interface IDistributedCache01 : IDistributedCache { ... }
public interface IDistributedCache02 : IDistributedCache { ... }

在启动期间的注册将如下所示:
services.AddSingleton<IDistributedCache01, SqlServerCache>();
services.AddSingleton<IDistributedCache02, SqlServerCache>();

然后你可以在构造函数中请求特定的缓存:
public MyController(IDistributedCache01 cache)
{
_cache = cache;
}

值得一看的是内置服务注册方法的实现。它们很简单。他们在这里为 AddDistributedRedisCacheAddDistributedSqlServerCache .

当我们拿出防御性编程时,注册方法就是两行代码:
services.AddSingleton<IDistributedCache, SqlServerCache>(); 
services.Configure(setupAction);

关于caching - IDistributedCache 的多个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com