Caching Values Inside HttpResponseMessage with Polly – caching series 2/3

Full source code here.

Want to learn more about Polly? Check out my Pluralsight course on it.

In this, the second of three posts on caching in Polly, I will show how to cache the values returned inside a HttpResponseMessage as opposed to caching the response with all its various elements.

The first post explained how to selectively cache a response, based on the Http StatusCode. The third post will show how to combine these two ideas and selectively cache the values inside the HttpResponseMessage.

Caching the whole response or the value

Caching the whole HttpResponseMessage is useful if your business logic depends on interrogating the response for values outside the main payload or you want a quick and easy caching solution.

If on the other hand, you only need the payload, there is no need to cache the whole response.

Both cases are plausible, and it is up to do decide which is more appropriate for your application.

How to cache the value inside HttpResponseMessage

The first step is to set the cache inside ConfigureServices.

1public void ConfigureServices(IServiceCollection services)
3    services.AddMemoryCache();
4    services.AddSingleton<IAsyncCacheProvider, MemoryCacheProvider>();

Then in Configure, setup the policy to store the type you expect to find in the response. In this example it is in a int, but it could easily be a complex layered model representing anything.

1public void Configure(IApplicationBuilder app, IHostingEnvironment env,
2    IAsyncCacheProvider cacheProvider, IPolicyRegistry<string> registry)
4    CachePolicy<int> cachePolicy =
5        Policy.CacheAsync<int>(cacheProvider, TimeSpan.FromSeconds(10));
7    registry.Add("CachingPolicy", cachePolicy);

Note, how I specified an int rather than a HttpResponseMessage.

In the previous post, I used the HttpClientFactory to select the policy from a Polly policy registry. I could do that because the type I was storing was HttpResponseMessage, that is not the case now and HttpClientFactory will not play nice when trying to cache anything other than a HttpResponseMessage. Instead I’m going to pass the policy registry directly to the controller and get the policy from this, I am still using the HttpClientFactory to pass HttpClient, but not for policy selection.

Here is how the controller starts.

 1public class CatalogController : Controller
 3    private readonly IHttpClientFactory _httpClientFactory;
 4    private readonly IPolicyRegistry<string> _policyRegistry;
 6    public CatalogController(IHttpClientFactory httpClientFactory, IPolicyRegistry<string> policyRegistry)
 7    {
 8        _httpClientFactory = httpClientFactory;
 9        _policyRegistry = policyRegistry;
10    }

And here is the GET method.

 2public async Task<IActionResult> Get(int id)
 4    string requestEndpoint = $"inventory/{id}";
 5    var httpClient = _httpClientFactory.CreateClient("RemoteServer");
 7    var cachePolicy = _policyRegistry.Get<CachePolicy<int>>("CachingPolicy");
 8    Context policyExecutionContext = new Context($"GetInventoryById-{id}");
10    int itemsInStock =
11        await cachePolicy.ExecuteAsync(context => GetItemsInStockCount(), policyExecutionContext);
13    async Task<int> GetItemsInStockCount()
14    {
15        HttpResponseMessage response = await httpClient.GetAsync(requestEndpoint);
17        if (response.IsSuccessStatusCode)
18        {
19            int itemsInStockCount = await response.Content.ReadAsAsync<int>();
20            return itemsInStockCount;
21        }
23        return 0;
24    }
26    return Ok(itemsInStock);

The first few lines are straight forward, setup the endpoint, get the HttpClient, get the cache policy. Like in the previous post, I use the context when placing items into the cache and retrieving them.

Because I want to cache the value inside the HttpResponse (and not the response itself) I can’t call the HttpClient from inside the policy’s exec method. Instead I need to call something that returns the int from inside the HttpResponse.

The easiest way of doing this is to use a local function which makes the HttpClient request, deserializes the response and returns the int from the response. In this post I am assuming that all values inside the response should be cached, I am NOT checking the status code of the response.

The policy then caches the int for the period specified in Startup.

That’s all there is to it.

If you are wondering how to selectively cache values inside the HttpResponse, tune in for the next post in this series.  
Full source code here.

comments powered by Disqus