首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Web中缓存搜索结果

在Web中缓存搜索结果
EN

Stack Overflow用户
提问于 2014-10-16 07:03:29
回答 2查看 2.8K关注 0票数 0

我在webapi中缓存 Get 方法和斜网,现在我想在另一个webapi方法 Search .So中使用相同的缓存输出,如何在搜索方法中访问缓存的Get结果?如何在其他方法中找到缓存密钥来使用它?

代码语言:javascript
复制
    [CacheOutput(ClientTimeSpan = 300, ServerTimeSpan = 300)]
    public IEnumerable<Movie> Get()
    {
        return repository.GetEmployees().OrderBy(c => c.MovieId);
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-16 12:25:17

与使用OutputCache不同,您可以考虑使用MemoryCache将结果存储在内存中,以获得更快的访问速度。

可以将结果存储在缓存中(例如:http://www.allinsight.de/caching-objects-in-net-with-memorycache/ )

代码语言:javascript
复制
//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
EN

Stack Overflow用户

发布于 2014-10-16 07:22:30

最简单的方法是将OutputCache属性添加到控制器中。它仅在MVC控制器中得到支持。对于Web控制器,可以使用此- https://github.com/filipw/AspNetWebApi-OutputCache

下面将每个搜索项的结果缓存24小时。然而,这种方法是幼稚的,只有当搜索词的数量很小时才有效。如果搜索词的数量很大(如本例中所示),则会增加巨大的内存压力,这将导致ASP.NET应用程序池循环,因此您将丢失缓存。

代码语言:javascript
复制
[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。它支持从缓存中删除项时的过期日期和回调函数。可以将电影列表添加到缓存中,然后查询缓存。只需确保在项过期时刷新/重新填充缓存。

代码语言:javascript
复制
System.Web.HttpRuntime.Cache.Add(
                key,
                value,
                null,
                expiration,
                Cache.NoSlidingExpiration,
                CacheItemPriority.Normal,
                callback);

我会在存储库中添加一个CachedRepository装饰器,您可以在控制器中引用它。在缓存的存储库中,如果存在缓存,我会尝试从缓存中返回数据。如果不是,我将从原始源获取和返回数据,并将其添加到缓存中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26398129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档