5

私は自分の Web API でキャッシングを探していました。そこでは、1 つの API メソッド (12 時間に 1 回変更される) の出力を後続の呼び出しに使用できます。その後、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
        }
4

1 に答える 1

10

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;
}
于 2014-10-27T08:22:16.407 に答える