gpt4 book ai didi

caching - 内存缓存 GetOrCreate 和 MemoryCacheEntryOptions

转载 作者:行者123 更新时间:2023-12-03 19:48:00 26 4
gpt4 key购买 nike

在当前实现中 IMemoryCache接口(interface)有以下方法:

bool TryGetValue(object key, out object value);
ICacheEntry CreateEntry(object key);
void Remove(object key);

我们可以通过以下方式查询缓存中的条目:
//first way
if (string.IsNullOrEmpty
(cache.Get<string>("timestamp")))
{
cache.Set<string>("timestamp", DateTime.Now.ToString());
}

//second way
if (!cache.TryGetValue<string>
("timestamp", out string timestamp))
{
//
cache.Set<string>("timestamp", DateTime.Now.ToString());
}

但是还有另一种方法可以使用工厂参数执行缓存应执行的操作( GetOrCreate):
public static TItem GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory)
{
object obj;
if (!cache.TryGetValue(key, out obj))
{
ICacheEntry entry = cache.CreateEntry(key);
obj = (object) factory(entry);
entry.SetValue(obj);
entry.Dispose();
}
return (TItem) obj;
}

正如您在上面看到的, Set方法接受 MemoryCacheEntryOptions或任何 absoluteExpirationRelativeToNow , absoluteExpiration , 等等日期 ( https://github.com/aspnet/Caching/blob/12f998d69703fb0f62b5cb1c123b76d63e0d04f0/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs),但是 GetOrCreate当我们创建一个新条目时,方法不支持那种类型的“per-entry-expiration-date”。

我想弄清楚我是否遗漏了什么,或者我是否应该做一个 PR 来添加这些方法。

附件:
public static ICacheEntry SetValue(this ICacheEntry entry, object value)
{
entry.Value = value;
return entry;
}

在这里打开一个问题: https://github.com/aspnet/Caching/issues/392为了得到更多的反馈。

最佳答案

我不确定我是否理解正确,但您可以在您收到的条目上设置所有“每个条目到期日期”选项作为工厂参数:

string timestamp = cache.GetOrCreate("timestamp", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);

return DateTime.Now.ToString();
});
string timestamp = cache.GetOrCreate("timestamp", entry =>
{
entry.SlidingExpiration = TimeSpan.FromSeconds(5);

return DateTime.Now.ToString();
});

所有 MemoryCacheEntryOptions可在 ICacheEntry 上获得.

关于caching - 内存缓存 GetOrCreate 和 MemoryCacheEntryOptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50247519/

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