gpt4 book ai didi

c# - 在 .Net 中使用 ObjectCache 缓存对象并过期

转载 作者:可可西里 更新时间:2023-11-01 09:10:52 25 4
gpt4 key购买 nike

我陷入了一个场景。我的代码如下:

更新:它与如何使用数据缓存无关,我已经在使用它及其工作,它是关于扩展它的,因此该方法不会在到期时间和从外部源获取新数据之间进行调用

object = (string)this.GetDataFromCache(cache, cacheKey);

if(String.IsNullOrEmpty(object))
{
// get the data. It takes 100ms
SetDataIntoCache(cache, cacheKey, object, DateTime.Now.AddMilliseconds(500));
}

因此,如果项目过期,用户会调用缓存并从中获取数据,并从服务中获取数据并保存以防万一,问题是,只要有待处理的请求(请求正在进行)服务发送另一个请求,因为对象已过期。最后应该有最多 2-3 次调用/秒,每秒有 10-20 次调用外部服务。

除了使用数组和时间戳等创建自己的自定义类之外,是否有任何最佳方法可以使请求时间之间没有冲突?

顺便说一句,缓存的保存代码是-

private void SetDataIntoCache(ObjectCache cacheStore, string cacheKey, object target, DateTime slidingExpirationDuration)
{
CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();

cacheItemPolicy.AbsoluteExpiration = slidingExpirationDuration;
cacheStore.Add(cacheKey, target, cacheItemPolicy);
}

最佳答案

使用Double-checked locking图案:

var cachedItem = (string)this.GetDataFromCache(cache, cacheKey);
if (String.IsNullOrEmpty(object)) { // if no cache yet, or is expired
lock (_lock) { // we lock only in this case
// you have to make one more check, another thread might have put item in cache already
cachedItem = (string)this.GetDataFromCache(cache, cacheKey);
if (String.IsNullOrEmpty(object)) {
//get the data. take 100ms
SetDataIntoCache(cache, cacheKey, cachedItem, DateTime.Now.AddMilliseconds(500));
}
}
}

这样,当您的缓存中有一个项目(因此,尚未过期)时,所有请求都将在不锁定的情况下完成。但是如果还没有缓存条目,或者它已过期 - 只有一个线程会获取数据并将其放入缓存中。确保您了解该模式,因为在 .NET 中实现它时有一些注意事项。

如评论中所述,没有必要使用一个“全局”锁对象来保护每个缓存访问。假设您的代码中有两个方法,并且每个方法都使用自己的缓存键(但仍使用相同的缓存)来缓存对象。然后你必须使用两个单独的锁对象,因为如果你将使用一个“全局”锁对象,对一个方法的调用将不必等待对另一个方法的调用,而它们永远不会使用相同的缓存键。

关于c# - 在 .Net 中使用 ObjectCache 缓存对象并过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32414054/

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