Implementing caching

When making a web request or calling a remote service, Polly can be used to cache the response from the remote service and improve the performance of the application's response time. The Polly cache is classified into two caches, known as the in-memory cache and the distributed cache. We will configure the in-memory cache in this section.

First, we need to add another Polly.Caching.MemoryCache package from NuGet. Once this is added, we will modify our Startup class and add the IPolicyRegistry as a member variable:

private IPolicyRegistry<string> _registry; 

In the ConfigurationServices method, we will initialize the registry and add it as a singleton object through DI:

_registry = new PolicyRegistry();
services.AddSingleton(_registry);

In the configure method, we will define the cache policy that takes the cache provider and the time to cache the responses. Since we are using in-memory cache, we will initialize the memory cache provider and specify it in the policy as follows:

Polly.Caching.MemoryCache.MemoryCacheProvider memoryCacheProvider = new MemoryCacheProvider(memoryCache); 
 
CachePolicy<HttpResponseMessage> cachePolicy = Policy.Cache<HttpResponseMessage>(memoryCacheProvider, TimeSpan.FromMinutes(10)); 

Finally, we will add the cachepolicy to our registry, which is initialized in the ConfigurationServices method. We named our registry cache:

_registry.Add("cache", cachePolicy); 

Modify our UserController class and declare the generic CachePolicy as follows:

CachePolicy<HttpResponseMessage> _cachePolicy;

We will now modify our UserController constructor and add the registry, which will be injected through the DI. This registry object is used to get the cache defined in the Configure method.

Here is the modified constructor of the UserController class:

public UserController(HttpClient client, IResilientHttpClient resilientClient, IPolicyRegistry<string> registry) 
{ 
  _client = client; 
  // _circuitBreakerPolicy = circuitBreakerPolicy; 
  _resilientClient = resilientClient; 
 
  _cachePolicy = registry.Get<CachePolicy<HttpResponseMessage>>("cache"); 
} 

Finally, we will define a GET method that calls another service to get the list of users and cache it in the memory. To cache the responses, we will wrap our custom resilient client GET method with the Execute method of the cache policy as follows:

[HttpGet] 
public async Task<IActionResult> Get() 
{ 
  //Specify the name of the Response. If the method is taking    
//parameter, we can append the actual parameter to cache unique
//responses separately Context policyExecutionContext = new Context($"GetUsers"); var response = _cachePolicy.Execute(()=>
_resilientClient.Get("http://localhost:7637/api/users"), policyExecutionContext); if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync(); return Ok(result); } return StatusCode((int)response.StatusCode, response.Content.ReadAsStringAsync()); }

When the request is returned, it will check whether the cache context is empty or expired, and the request will be cached for 10 minutes. All subsequent requests during that time will read the response from the in-memory cache store. Once the cache has expired, based on the set time limit, it will invoke the remote service again and cache the response.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.185.155