Raz*_*tru 5 caching asp.net-core
在当前的实现IMemoryCache接口中有以下方法:
bool TryGetValue(object key, out object value);
ICacheEntry CreateEntry(object key);
void Remove(object key);
Run Code Online (Sandbox Code Playgroud)
我们可以通过以下方式查询缓存中的条目:
//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());
}
Run Code Online (Sandbox Code Playgroud)
但是还有另一种方法应该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;
}
Run Code Online (Sandbox Code Playgroud)
As you can see above, the Set method accepts MemoryCacheEntryOptions or any absoluteExpirationRelativeToNow, absoluteExpiration, etc dates (https://github.com/aspnet/Caching/blob/12f998d69703fb0f62b5cb1c123b76d63e0d04f0/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs), but GetOrCreate method doesn't support that type of 'per-entry-expiration-date' for when we create a new entry.
I'm trying to figure out if i'm missing something or if i should do a PR to add those methods.
Annex:
public static ICacheEntry SetValue(this ICacheEntry entry, object value)
{
entry.Value = value;
return entry;
}
Run Code Online (Sandbox Code Playgroud)
Opened an issue here: https://github.com/aspnet/Caching/issues/392 in order to get some more feedback.
tpe*_*zek 11
我不确定我是否理解正确,但是您可以将收到的条目上的所有“每条目到期日期”选项设置为工厂的参数:
string timestamp = cache.GetOrCreate("timestamp", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);
return DateTime.Now.ToString();
});
Run Code Online (Sandbox Code Playgroud)
string timestamp = cache.GetOrCreate("timestamp", entry =>
{
entry.SlidingExpiration = TimeSpan.FromSeconds(5);
return DateTime.Now.ToString();
});
Run Code Online (Sandbox Code Playgroud)
所有这些MemoryCacheEntryOptions都可以在ICacheEntry.
| 归档时间: |
|
| 查看次数: |
6902 次 |
| 最近记录: |