c# - Web API 中的内存缓存

标签 c# asp.net-mvc asp.net-web-api asp.net-web-api2 memorycache

我正在寻找 Caching在我的 web api 中,我可以使用一个 api 方法的输出(每 12 小时更改一次)进行后续调用,然后我发现 this solution在 SO 上,但我很难理解和使用下面的代码

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
}

我不确定如何在以下上下文中调用和使用此方法? 我有一个方法 Get

  public IEnumerable<Employee> Get()
    {
        return repository.GetEmployees().OrderBy(c => c.EmpId);
    }

我想缓存 Get 的输出并在我的其他方法 GetEmployeeById() 或 Search() 中使用它

        public Movie GetEmployeeById(int EmpId)
        {
           //Search Employee in Cached Get
        }

        public IEnumerable<Employee> GetEmployeeBySearchString(string searchstr)
        {
          //Search in Cached Get
        }

最佳答案

我更新了您的方法以返回类而不是 IEnumberable:

private TEntity GetFromCache<TEntity>(string key, Func<TEntity> valueFactory) where TEntity : class 
{
    ObjectCache cache = MemoryCache.Default;
    // the lazy class provides lazy initializtion which will eavaluate the valueFactory expression only if the item does not exist in cache
    var newValue = new Lazy<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<TEntity>;
    return (value ?? newValue).Value; // Lazy<T> handles the locking itself
}

然后你可以像这样使用这个方法:

public Movie GetMovieById(int movieId)
{
    var cacheKey = "movie" + movieId;
    var movie = GetFromCache<Movie>(cacheKey, () => {       
        // load movie from DB
        return context.Movies.First(x => x.Id == movieId); 
    });
    return movie;
}

和搜索电影

[ActionName("Search")]
public IEnumerable<Movie> GetMovieBySearchParameter(string searchstr)
{
     var cacheKey = "movies" + searchstr;
     var movies = GetFromCache<IEnumerable<Movie>>(cacheKey, () => {               
          return repository.GetMovies().OrderBy(c => c.MovieId).ToList(); 
     });
     return movies;
}

关于c# - Web API 中的内存缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26581065/

相关文章:

c# - 如何将日期从一种文化转换为另一种文化?

asp.net-mvc - 将 asp.net mvc ajax actionlink 重写为 jquery/ajax 语句

html - MVC 3 数据注释 : Not allow HTML

javascript - ASP.NET MVC 5 - jQuery AJAX 有效,Fetch API 无效

c# - 禁止 ASP.NET Web API 上具有空值的属性

c# - 如何从 C# 中的字符串中选择一个数字

c# - 在构造函数中调用异步方法?

asp.net-mvc - 如何将 Ninject 与 ASP.NET Web API 一起使用?

c# - 如何使用c#检查xml文件是否为空

c# - 使用 <a> 标签强制下载 pdf