gpt4 book ai didi

在 Web API 中缓存数据

转载 作者:行者123 更新时间:2023-12-03 07:38:37 24 4
gpt4 key购买 nike

我需要缓存大部分静态的对象集合(每天可能会更改 1 次),这些对象在我的 ASP.NET Web API OData 服务中可用。该结果集跨调用使用(意味着不是特定于客户端调用),因此需要在应用程序级别缓存。

我对“Web API 中的缓存”进行了大量搜索,但所有结果都与“输出缓存”有关。这不是我在这里寻找的。我想缓存一个“People”集合,以便在后续调用中重用(可能有滑动过期时间)。

我的问题是,由于这仍然只是 ASP.NET,我是否使用传统的应用程序缓存技术将该集合保留在内存中,或者我还需要做其他事情?该集合不会直接返回给用户,而是通过 API 调用用作 OData 查询的幕后来源。我没有理由在每次调用时都访问数据库来获取每次调用完全相同的信息。每小时过期就足够了。

有人知道如何在这种情况下正确缓存数据吗?

最佳答案

我最终使用的解决方案涉及 MemoryCacheSystem.Runtime.Caching命名空间。以下是最终用于缓存我的集合的代码:

//If the data exists in cache, pull it from there, otherwise make a call to database to get the data
ObjectCache cache = MemoryCache.Default;

var peopleData = cache.Get("PeopleData") as List<People>;
if (peopleData != null)
return peopleData ;

peopleData = GetAllPeople();
CacheItemPolicy policy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30)};
cache.Add("PeopleData", peopleData, policy);
return peopleData;

这是我发现使用 Lazy<T> 的另一种方法考虑锁定和并发性。这篇文章的总功劳:How to deal with costly building operations using MemoryCache?

private IEnumerable<TEntity> GetFromCache<TEntity>(string key, Func<IEnumerable<TEntity>> valueFactory) where TEntity : class 
{
ObjectCache cache = MemoryCache.Default;
var newValue = new Lazy<IEnumerable<TEntity>>(valueFactory);
CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30) };
//The line below returns existing item or adds the new value if it doesn't exist
var value = cache.AddOrGetExisting(key, newValue, policy) as Lazy<IEnumerable<TEntity>>;
return (value ?? newValue).Value; // Lazy<T> handles the locking itself
}

关于在 Web API 中缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16443795/

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