Introduction
Highly scalable applications that have to serve millions of users everyday are in need of a highly-scalable, highly available, and durable caching platform and architecture. Distributed caching nodes are almost always the best solution to avoid unnecessary round-trips to the database, but they can also be a cause of problems and issues if it implemented incorrectly. Possible problems would be using out-of-date objects holding an older version of data, or failing to retrieve the correct, not necessarily the latest, version of an object from the cache, or expiring an object too soon from the cache.
One of the most anticipated features has been significantly enhanced at the latest CTP version of Windows Azure AppFabric. Caching was introduced back in PDC '10 along with other features like durable messages on Service Bus, more identity providers for Identity Federation, VM Role, Extra small Instances, SQL Azure Reporting, Windows Azure Connect, and a lot of others.
This article is based on Visual Studio 2010 using the latest version of the Windows Azure SDK v1.3 at the time it was published, and also Windows Azure AppFabric SDK v2.0 CTP February release.
Background
Back in the days, Windows Azure AppFabric Cache was referred by the name of "Velocity", but this is not only part of Windows Azure AppFabric, but also part of Windows Server AppFabric which also includes a project referred to by the codename "Dublin". "Dublin" was also demonstrated as a composite building service, where you select all the necessary components of your application and along with WCF and WF hosting and orchestration, you get a lot of new things, like easy scaling, and point and click type of adding new components/services to your application. All of those are just a quick overview of what is included on the Windows Azure/Server AppFabric family. Be aware because they are not aligned, which means that if something exists in Windows Azure AppFabric, it doesn't mean that it exists on the Windows Server AppFabric also.
What is it?
Windows Azure AppFabric Cache removes all the hassle from having to setup a new caching farm with nodes and setting up all the necessary settings to keep those nodes in sync, making sure that nodes have enough resources etc., by providing a Platform as a Service approach just like the whole Windows Azure Platform does. All you have to do is, go to http://portal.appfabriclabs.com, and sign up and start using all the services Windows Azure AppFabric has to offer, ACL, Service bus, and Caching among others.
How does it work?
Just as any other distributed caching solution, Windows Azure AppFabric Cache has two parts. The server part where the service is running and the client part where the client is using some code and configuration to access it. To create the server part, you have to go to the Windows Azure AppFabric Labs portal mentioned above and select "Cache".
After that, you have to click on "Create Namespace".
There you have to select a subscription to activate the feature. As this is a CTP feature, you won't have any subscription created at the moment, so you'll be prompted by the portal to automatically create one. As you click OK, you'll get a new subscription called "LabsSubscription". Everything will be associated with this subscription as you cannot create a new one on the CTP. When the subscription is ready (takes 3-4 seconds), you have to select a name for your namespace and then check if it's available, then select the Region (only USA is available for the CTP), and finally choose the cache size, either 128 MB or 256 MB. You can change the cache size once every 24 hours if you want.
Now you can click OK and the namespace will be in an "Activating" state for a while.
When it's ready, it will turn green and the indication will be "Activated" which means you can now use it in your application. As I said, the application has two parts; we just activated the server part and we're going to create the client configuration now to access the service. This part is also being done automatically by the portal.
All you have to do is click OK, "View Client Configuration", and select the correct part of the configuration you need, either for a non-Web Application or a Web Application where you can change the session state persistence storage to this cache. From the same menu, you can also change the cache size by clicking on "Change Cache Size". If you click on "View Client Configuration", you get a window containing all the necessary XML you need to put into your app.config or web.config.
After you select the part you need for your application, which in my case is a simple console application to do some very basic demonstration about how to use the cache, you have to place it inside your app.config.
<configuration>
<configsections>
<section name="dataCacheClient"
type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
Microsoft.ApplicationServer.Caching.Core"
allowlocation="true" allowdefinition="Everywhere">
</section></configsections>
<datacacheclient deployment="Simple">
<hosts>
<host name="YOUR_NAMESPACE.cache.appfabriclabs.com"
cacheport="22233">
</host></hosts>
<securityproperties mode="Message">
<messagesecurity authorizationinfo="YOUR_KEY_HERE">
</messagesecurity></securityproperties>
</datacacheclient>
</configuration>
Using the code
When you're done adding this XML to your app.config, you'll have to reference two assemblies from the Windows Azure AppFabric SDK v2.0, which you can download here. The assemblies you need are located in \Program Files\Windows Azure AppFabric SDK\V2.0\Assemblies\Cache\ and you need to put a reference on Microsoft.ApplicationServer.Caching.Core.dll and Microsoft.ApplicationServer.Caching.Client.dll.
Adding those two references will allow all the necessary methods and namespaces to be exposed and be used by your code. We particularly need the DataCacheFactory
and DataCache
classes which contain all the necessary methods to initialize the cache client and interact with the service.
using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
{
DataCache dataCache = dataCacheFactory.GetDefaultCache();
}
As we don't provide any parameters, the default values read from the configuration file will be initialized and used by the DataCache
client.
Using the DataCache
client is fairly easy, and it's just like any other distributed cache. It has methods to Put()
something in the cache, Get()
something from the cache etc. Whenever you Put or Get something from the cache, you have to specify a key that is unique to this object. In our case, I'm using the FullName
of our Person
class which is returned by a method of the class.
dataCache.Put(nPerson.GetFullName(), nPerson);
Person cachedPerson = (Person)dataCache.Get(nPerson.GetFullName());
You might notice that the Person
class is decorated with a DataContract
attribute and all the properties are decorated with a DataMember
attribute. That is needed so the object can be serialized and stored into the cache. Both attributes exist in the System.ServiceModel
assembly for which you also have to add a reference to your project. The assembly is located in the GAC as it is part of the .NET Framework.
[DataContract]
public class Person
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string Lastname { get; set; }
[DataMember]
private decimal Money { get; set; }
public Person(string firstname, string lastname)
{
FirstName = firstname;
Lastname = lastname;
Money = 0;
}
public decimal WithdrawMoney(decimal amount)
{
return Money -= amount;
}
public void DepositMoney(decimal amount)
{
Money += amount;
}
public decimal GetBalance()
{
return Money;
}
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, Lastname);
}
}
There are other aspects of the Windows Azure AppFabric Cache that I'll explore in future articles, like how to get an object only if it's newer than the version already in the memory, or how to handle versioning of multiple objects in the cache and how to automatically remove an object from the cache after a specific period of time.
All the code is inside Program.cs:
using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
{
DataCache dataCache = dataCacheFactory.GetDefaultCache();
Person nPerson = new Person("Panagiotis", "Kefalidis");
Console.WriteLine(string.Format("Currently in your account: {0}",
nPerson.GetBalance()));
nPerson.DepositMoney(100);
Console.WriteLine(string.Format("Currently in your " +
"account after deposit: {0}", nPerson.GetBalance()));
dataCache.Put(nPerson.GetFullName(), nPerson);
nPerson.WithdrawMoney(50);
Person cachedPerson = (Person)dataCache.Get(nPerson.GetFullName());
Console.WriteLine(string.Format("Currently in your " +
"cached account after withdraw: {0}", cachedPerson.GetBalance()));
Console.WriteLine(string.Format("Currently in your account " +
"after withdraw: {0}", nPerson.GetBalance()));
dataCache.Put(nPerson.GetFullName(), nPerson);
}
Console.ReadKey();
Points of interest
You can learn more about caching at this URL: http://msdn.microsoft.com/en-us/library/ee790954.aspx. Be aware that this is referring to Windows Server AppFabric and not Windows Azure AppFabric, but it is a very good source to learn more and get an overview of what the underlying infrastructure is.
You can also get more information about the Windows Azure platform in general at my blog: http://www.kefalidis.me.
History
- 16/02/2011: First version published.