Caching is one of the ways to achieve performance gains by serving request from a temporary location instead of calling backend resources for consequential requests. It is especially critical when considering most of the response times –throughput – take place during backend processes. In this post, I will explain how-to caching for cloud services with demonstration of a sample application.
I will be using the solution that I have used for the previous post as base for this exercise. The demonstration will include very simple case - caching the to-do list retrieved from Azure SQL database and responding all the list queries from there.
1: using System.Collections.Generic;
2: using System.Diagnostics;
3: using System.Linq;
4: using System.Web.Mvc;
5: using Microsoft.ApplicationServer.Caching;
6: using ToDoData.Models;
7:
8: namespace ToDoListWeb2.Controllers
9: {
10: //[Authorize]
11: //[InitializeSimpleMembership]
12: public class TaskController : Controller
13: {
14: private const string CacheKey = "CachedTasks";
15: readonly DataCache _dataCache = new DataCache("default");
16:
17: //
18: // GET: /Home/
19:
20: public ActionResult Index()
21: {
22: return View(GetDataList());
23: //Util.TestTrace2();
24: //using (var context = new ToDoContext())
25: // return View(context.ToDoItems.ToList());
26: }
27:
28: private List<ToDoItem> GetDataList()
29: {
30: if (_dataCache.Get(CacheKey) == null)
31: {
32: Trace.TraceInformation("Cache with key '{0}' getting filled.", CacheKey);
33: using (var context = new ToDoContext())
34: {
35: _dataCache.Add(CacheKey, context.ToDoItems.ToList());
36: }
37: }
38: else
39: Trace.TraceInformation("Serving the request from the Cache with key '{0}'.", CacheKey);
40:
41: return (List<ToDoItem>)_dataCache[CacheKey];
42: }
43:
44: //
45: // GET: /Home/Details/5
46:
47: public ActionResult Details(int id = 0)
48: {
49: using (var context = new ToDoContext())
50: return View(context.ToDoItems.Find(id));
51: }
52: }
53: }
Before deployment we need to modify these (at least)
1: <dataCacheClients>
2: <dataCacheClient name="default">
3: <autoDiscover isEnabled="true" identifier="ToDoListWeb2" />
4: <!--<localCache isEnabled="true" sync="TimeoutBased" objectCount="100000" ttlValue="300" />-->
5: </dataCacheClient>
6: </dataCacheClients>
As you can see, from the image below, first the cache is filled with data (1st request), then cache data used (consequential requests) directly.