Caching is a powerful tool for applications and serves as a basis for many architectural patterns around data. There are several examples of caching being utilized in architectural patterns including the cache-aside pattern and the sharding pattern. By using a cache, applications can scale without being bottlenecked at the data tier. A cache provides a high-throughput, low latency data layer that helps minimize resource use by compute resources even during periods of high request volume. Applications in the cloud stand to gain a great deal from a distributed cache that will scale and grow with the applications that utilize it.

Microsoft currently provides Azure Redis Cache as the de facto cache option for cloud developers. Microsoft used to offer Azure Managed Cache Service and In Role Caching, but both have been deprecated and will be completely shutdown and no longer supported on 11/30/2016. Microsoft has stated that the deprecated services only still exist to support existing applications and all new development that requires a cache should use Azure Redis Cache.

If you're not familiar with Redis Cache here is the description directly from their website:

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache, and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

Azure Redis Cache is simply an Azure hosted version of Redis that offers all the same functionality as Redis but is hosted in Microsoft's Azure cloud.

In this blog I'm going to focus on several ways a developer can utilize Azure Redis in a .Net application.

Creating an Azure Redis Cache

To create an Azure Redis Cache simply visit the Azure Portal and select Redis Caches. Once there, click "Add" and fill out the various required fields as desired.

Azure Redis Cache List

Azure Redis Cache Setup

You're done! Once the cache is finished deploying you will have a fully functional, cloud hosted Redis cache.

Using Azure Redis

Storing Session State in Azure Redis

Sometimes your web application requires state but cookies aren't sufficient for your needs. Session state provides a server managed state mechanism that can help meet an application's needs for storing state. Microsoft has provided a way to easily integrate Azure Redis Cache with shared session in .Net applications.

First, you'll need to install the required Nuget packages into your project. Click on "Manage Nuget Packages" in your project and search for RedisSessionStateProvider. You should see Microsoft.Web.RedisSessionStateProvider by Microsoft. Click on that one and install it. Next you'll need to configure the applications shared session state to use the Azure Redis Cache you have created. To do this you'll need to modify the sessionState portion of the Web.config

Once you have the config done, you're ready to start utilizing the cache as normal. An example controller is shown below:

public class HomeController : Controller
{
 public ActionResult Index()
 {
 object value = Session["Home"];
 int result = 0;
 if (value != null)
 {
 result = (int)value;
 Session["Home"] = ++result;
 }
 else
 {
 Session["Home"] = 1;
 }
 return View();
 }
 
 public ActionResult About()
 {
 object value = Session["Home"];
 string home = "not set";
 if(value != null)
 {
 home = ((int)value).ToString();
 }
 ViewBag.Message = string.Format("The cache value for Home is {0}", home);
 return View();
 }
 
 public ActionResult Contact()
 {
 ViewBag.Message = "Your contact page.";
 return View();
 }
}

In this example we're simply storing and incrementing a session state value in the Index action of the Home controller. Anytime a user visits the root page of the site then the Home value for the cache will be set to one or incremented by one when a user visits the homepage. In the About action we retrieve the value from session state and then pass it to the view to be displayed on the about page.

A few notes about using Azure Redis Cache for Session State:

  • Data types must be serializable
  • Make sure to remove the InProc session state provider if you were using that before from the Web.config

Storing Html Output Cache in Azure Redis

The output cache is a great way to improve your sites performance by storing html in a cache to reduce response times and load for your site. Microsoft has also provided a way to easily configure your .Net application to use Azure Redis Cache for an Html output cache.

The first step is to add the Nuget package to your project. Click on "Manage Nuget Packages" in your project and search for RedisOutputCacheProvider. You should see Microsoft.Web.RedisOutputCacheProvider by Microsoft. Click on that one and install it. Next is to configure the output cache to use the Azure Redis Cache by altering the caching section in the Web.config.


Notice I define the database ID to be 1. By default Azure Redis Cache has 16 databases and you can configure which database you want the cache to use in the Web.config. I configured the output cache to use database 1 because session state is using database 0 and I don't want any of my keys to potentially conflict between session state and the html output cache.

Now you can start defining what you want to store in the output cache. You can do this in the controller or in a view. You can simply specify a controller action result to store in the output cache by adding the OutputCache attribute to the action method.

[OutputCache(Duration = 1200, VaryByParam = "*")]
public ActionResult Contact()
{
 ViewBag.Message = "Your contact page.";
 return View();
}

You can also specify in the view by doing

@{
 ViewBag.Title = "Contact";
 Response.OutputCache(1200);
}

This very simple code will store the pages in the cache for the specified amount of time. You can also configure the cache to vary by headers, parameters, etc.

Custom use of the Azure Redis Cache

Of course you can also use the Azure Redis Cache in any way you want. To configure the Azure Redis Cache for general use, simply install the StackExchange.Redis by Stack Exchange Nuget package. Once installed, you can connect and interact with the cache easily. Below is a sample controller which utilizes a connection to the cache to increment a value. That value is also retrieved and displayed on a different view utilizing the same connection property.

public ActionResult CustomCachePage()
{
 // Connection refers to a property that returns a ConnectionMultiplexer.
 var cache = Connection.GetDatabase(db: 2);
 var custom = cache.StringIncrement("Custom");
 ViewBag.Message = string.Format("The cache value for Custom is {0}", custom);
 return View();
 }
 
 
 private static Lazy lazyConnection = new Lazy(() =>
 {
 return ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["CustomCache"].ConnectionString);
 });
 
 private static ConnectionMultiplexer Connection
 {
 get
 {
 return lazyConnection.Value;
 }
 }

Conclusion

As I have shown here with some trivial examples, you can utilize Azure Redis Cache in a number of ways. It serves as a great way to connect a .Net application to a lightning fast in memory key/value cache. What I have shown barely scratches the surface of the many pieces of functionality Azure Redis Cache provides. It can be used in a variety of enterprise applications to provide caching in front of a more persistent data store or as a message broker. Overall, Azure Redis Cache is a great PaaS solution for caching in enterprise .Net applications.

About the Author

Casey SilverCasey Silver is a Software Engineer in CapTech's Application Development Practice Area, where he specializes in developing .Net and cloud based applications.