我在webapi中缓存 Get 方法和斜网,现在我想在另一个webapi方法 Search .So中使用相同的缓存输出,如何在搜索方法中访问缓存的Get结果?如何在其他方法中找到缓存密钥来使用它?
[CacheOutput(ClientTimeSpan = 300, ServerTimeSpan = 300)]
public IEnumerable<Movie> Get()
{
return repository.GetEmployees().OrderBy(c => c.MovieId);
}发布于 2014-10-16 12:25:17
与使用OutputCache不同,您可以考虑使用MemoryCache将结果存储在内存中,以获得更快的访问速度。
可以将结果存储在缓存中(例如: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/
发布于 2014-10-16 07:22:30
最简单的方法是将OutputCache属性添加到控制器中。它仅在MVC控制器中得到支持。对于Web控制器,可以使用此- 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装饰器,您可以在控制器中引用它。在缓存的存储库中,如果存在缓存,我会尝试从缓存中返回数据。如果不是,我将从原始源获取和返回数据,并将其添加到缓存中。
https://stackoverflow.com/questions/26398129
复制相似问题