Tuesday 20 October 2015

WebApi Cache using CacheCow and SQL Server persistancy

I wrote how to implement in-memory cache in this post. But this solution is not good if we want to host our Api in a web farm or if we are going to use load balancing. The best approach is using DB persistence to hold the cache.

Fortunately, CacheCow gives us the SQL Server implementation. Following are the configurations we need to made in order to activate this.
Refer following NuGet into your project.

Install-Package CacheCow.Server.EntityTagStore.SqlServer

In the WebApiConfig.cs file add the following code.
 
 var connString = System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conn_Str"].ConnectionString;
 var eTagStore = new SqlServerEntityTagStore(connString);  
 var cacheCowCacheHandler = new CachingHandler(config,eTagStore); 
 cacheCowCacheHandler.AddLastModifiedHeader = false;
 config.MessageHandlers.Add(cacheCowCacheHandler);

Now this code would not run as it is. Because we need to do required changes to the DB as well. The required sql scripts are getting download along with the NuGet package. Execute that script against your DB. It would create a table CacheState and other relevant procedures.

Now the CacheCow DB persistence is done.Lets shoot some Web API and requests and test results.

When we are doing our initial Get request to a WebApi resource, the fiddler looks like as follows. Check the  request and response headers .


you can clearly see that its responded with status 200 - Ok. Following is the status of the CacheState now.

You can clearly see that the ETag is created and saved in the DB.
If we are going to do the same GET request again, we would get the 304 from server.

You can clearly see that the request been made to the server with the ETag If-None-Match. Server get the ETag and responded with 304 Not Modified. So no need to get the resource back again. ie: Client has the latest version.

No comments:

Post a Comment