web api中的内存缓存
我在我的web api中寻找缓存 ,我可以使用一个api方法的输出(在12小时内更改一次)进行后续调用,然后我在SO上找到了这个解决方案 ,但是我很难理解并使用下面的代码
private IEnumerable GetFromCache(string key, Func<IEnumerable> valueFactory) where TEntity : class { ObjectCache cache = MemoryCache.Default; var newValue = new Lazy<IEnumerable>(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>; return (value ?? newValue).Value; // Lazy handles the locking itself }
我不确定如何在下面的上下文中调用和使用此方法? 我有一个方法Get
public IEnumerable Get() { return repository.GetEmployees().OrderBy(c => c.EmpId); }
我想缓存Get的输出并在我的其他方法GetEmployeeById()或Search()中使用它
public Movie GetEmployeeById(int EmpId) { //Search Employee in Cached Get } public IEnumerable GetEmployeeBySearchString(string searchstr) { //Search in Cached Get }
我更新了您的方法以返回类而不是IEnumberable:
private TEntity GetFromCache(string key, Func 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 (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 ; return (value ?? newValue).Value; // Lazy handles the locking itself }
那么你可以使用这种方法:
public Movie GetMovieById(int movieId) { var cacheKey = "movie" + movieId; var movie = GetFromCache(cacheKey, () => { // load movie from DB return context.Movies.First(x => x.Id == movieId); }); return movie; }
并搜索电影
[ActionName("Search")] public IEnumerable GetMovieBySearchParameter(string searchstr) { var cacheKey = "movies" + searchstr; var movies = GetFromCache>(cacheKey, () => { return repository.GetMovies().OrderBy(c => c.MovieId).ToList(); }); return movies; }