Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Cache in web api

I was looking for Caching in my web api where i can use output of one api method(that changes once in 12hrs) for subsequesnt calls and then i found this solution on SO,but i am having a difficulty in understanding and using the below code

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
}

I am not sure how to call and use this method in below context? I have a method Get

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

and i want to cache the output of Get and use it in my other methods GetEmployeeById() or Search()

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

        public IEnumerable<Employee> GetEmployeeBySearchString(string searchstr)
        {
          //Search in Cached Get
        }
like image 249
F11 Avatar asked Oct 27 '14 04:10

F11


People also ask

Is caching possible in Web API?

Caching is very common to make applications performant and scalable. If a result is already computed by the application, it is cached in a store so that next time when the same request comes, cached result can be fetched instead of processing the request again.

What is caching in Web API?

Caching is a technique of storing frequently used data or information in a local memory, for a certain time period. So, next time, when the client requests the same information, instead of retrieving the information from the database, it will give the information from the local memory.

How do I cache data in Web API?

To cache the data being returned from ASP.NET Web API, we can use MemoryCache object that is the part of System. Runtime. Cache namespace. Please note that OutputCache attributes to the controller action method of ASP.NET MVC is not supported in ASP.NET Web API.


1 Answers

I updated your method to return classes instead of 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
}

then you can use this method like:

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;
}

and to search movies

[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;
}
like image 51
Marian Ban Avatar answered Sep 21 '22 11:09

Marian Ban