web api中的内存缓存

本文关键字:内存 缓存 api web | 更新日期: 2023-09-27 18:27:52

我在我的web api中寻找Caching,在那里我可以使用一个api方法的输出(12小时内更改一次)进行subsquesnt调用,然后我在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
}

我不知道如何在下面的上下文中调用和使用此方法我有一个方法获取

  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
        }

web api中的内存缓存

我更新了您的方法以返回类,而不是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;
}