我正在使用strathweb在webapi中缓存获取方法,现在我想在我的另一个webapi方法中使用相同的缓存输出搜索。所以如何访问缓存在搜索方法中获取结果?如何找到缓存密钥以在其他方法中使用它?
[CacheOutput(ClientTimeSpan = 300, ServerTimeSpan = 300)]
public IEnumerable<Movie> Get()
{
return repository.GetEmployees().OrderBy(c => c.MovieId);
}
答案 0 :(得分:1)
您可以考虑使用MemoryCache
将结果存储在内存中,以便更快地访问,而不是使用OutputCache
。
您可以将结果存储在缓存中(以下示例为例:http://www.allinsight.de/caching-objects-in-net-with-memorycache/
//Get the default MemoryCache to cache objects in memory
private ObjectCache cache; = MemoryCache.Default;
private CacheItemPolicy policy;
public ControllerConstructor()
{
cache = MemoryCache.Default;
policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30);
}
public IEnumerable<Movie> GetMovieBySearchParameter(string searchstr)
{
if (cache.Get(searchstr) != null)
{
return cache.Get(searchstr) as IEnumerable<Movie>;
}
// Do the search and get the results.
IEnumerable<Movie> result = GetMovies(blah.....);
// Store the results in cache.
cache.Add(searchstr, result, policy);
}
以上情况非常粗糙(我现在没有VS在我面前试试),但希望核心想法能够实现。
http://www.allinsight.de/caching-objects-in-net-with-memorycache/
答案 1 :(得分:0)
最简单的方法是将OutputCache属性添加到控制器中。它仅在MVC控制器中受支持。对于Web API控制器,您可以使用此 - https://github.com/filipw/AspNetWebApi-OutputCache
以下内容将每个搜索字词的结果缓存24小时。但是,这种方法很幼稚,只有当搜索项的数量非常小时才有效。如果搜索项的数量很大(就像在这种情况下那样),它会增加巨大的内存压力,这将导致ASP.NET应用程序池回收,因此您将丢失缓存。
[OutputCache(Duration=86400, VaryByParam="searchstr")] // for MVC
[CacheOutput(ClientTimeSpan = 50, ServerTimeSpan = 50)] // for Web API
[ActionName("Search")]
public IEnumerable<Movie> GetMovieBySearchParameter(string searchstr)
{
}
在您的情况下,整个结果集可以缓存一次,并且可以每24小时更新一次。您可以查看System.Web.HttpRuntime.Cache。当项目从缓存中删除时,它支持到期日期和回调函数。您可以将影片列表添加到缓存,然后查询缓存。只需确保在项目到期时刷新/重新填充缓存。
System.Web.HttpRuntime.Cache.Add(
key,
value,
null,
expiration,
Cache.NoSlidingExpiration,
CacheItemPriority.Normal,
callback);
我会将CachedRepository装饰器添加到您在控制器中引用的存储库中。在该缓存的存储库中,如果存在,我会尝试从缓存中返回数据。如果不是,我将从原始源获取并返回数据,并将其添加到缓存中。