Home > C#, WCF > Caching in WCF Services: Part 2 AppFabric distributed cache

Caching in WCF Services: Part 2 AppFabric distributed cache

Introduction

A couple of months ago, I wrote an article about caching in WCF using the in-process memory cache available in the .NET 4.0 framework. This component offers a lightweight caching solution that can easily be integrated in various types of .NET applications.

There are scenarios where a more advanced caching solution is required. The standard .NET 4.0 cache cannot be shared among multiple servers. Every server has its own isolated instance of the cache. Furthermore, it shares memory with the application. A 32-bit application can allocate at maximum 4 GB of RAM (on a 64-bit OS; maximum 2GB of RAM on a 32-bit OS). There can be situations where you want that the cache of a 32-bit app is larger than 2 GB (although these situations are rare).

AppFabric

Microsoft offers a distributed cache as part of Windows Server AppFabric. This cache can be installed on Window Server 2008 and higher. It is also available in the cloud on Windows Azure. The AppFabric cache is a distributed out of process cache; this means that the cache can be shared among multiple servers and applications. Because it runs outside the application process, it can survive application shut downs and it can be larger then 4 GB for 32-bit applications.

You can deploy AppFabric in two ways on your network: on every application server hosting your application or as a separate infrastructure layer independent of your application servers. The lather provides more flexibility in terms of being able to scale your caching and application server layers independent of each other, but it comes at a higher cost of servers and an increased latency to access the cache.

caching_options

Configuring the AppFabric caching server

AppFabric can be download for free from the Microsoft download site. At the moment of writing, the latest version available is AppFabric 1.1. It requires at least Windows Vista or Windows Server 2008. For testing the AppFabric cache, I have setup a Windows Server 2008 R2 VM configured in workgroup modus. I choose to deploy my WCF service, on a separate server.

Prior to the installation of AppFabric, I created a technical user account called “AppFabricCacheUser” that will be used to run the caching service. I also created a network share called “AppFabricCache”. If you would use multiple servers, the same user account must be created on all the servers. These user accounts must have the same password on all servers. Only one server must host a network share for the AppFabric cache. The AppFabric user account must have admin rights on the server hosting the share.

Please note: the configuration of AppFabric is different in case your servers are part of an AD domain. Then you don’t need to setup a network share or separate technical accounts on each server. Most companies should have an AD domain. Please consult the AppFabric MSDN pages for more information. I recommend to only use AppFabric caching in workgroup mode in a sandboxed test environment. Otherwise, always use it in AD mode if possible.

AppFabric consists of two parts, the hosting features and the distributed cache. Because this article is about caching, I only installed the necessary caching features.

setup

After the installation is finished, we must launch the “AppFabric Server Configuration Wizard”. We must specify the Caching Service account we created earlier, the XML Caching Service configuration provider and the file share we created earlier.

configure_workgroup_modus

After this is done, press “next” to continue to following screen. On this screen, we can change the network ports if needed. I choose to stick with the defaults.

configure_cache_node

Now this is done, we can start our cache using the PowerShell. In order to do this, launch the “Caching Administration Windows PowerShell” and enter the following command: Start-CacheCluster.

By default, security is enabled on the cache. So we must grant access to our client. Because I run in workgroup modus, I must create an account on my server with the exact same user name and password as will be used by my WCF service on the AppFabric caching client. Granting access to a user account can be done with the following command: Grant-CacheAllowedClientAccount -Account “YourUserAccountName”.

Please note: in case of an AD domain is available, the user account must not be created on the server. It is sufficient that the account is known in AD.

powershell_cmdlets

Configuring the AppFabric caching client

On the client, the client at least the “Cache Client” of AppFabric must be installed. No special configuration is required.

setup_client

Developing the WCF service

For the sake of simplicity, I kept the actual programming code to the strict minimum. The sample WCF application consists of two components: a (slow) repository and a WCF service.

First we must add a reference to two DLL’s installed by the AppFabric installer. They can be found in the installation folder of AppFabric.

vs_references

The slow repository is called: SlowRepository (very creative naming; I know…)

public class SlowRepository
{
    public IEnumerable<string> GetPizzas()
    {
        Thread.Sleep(10000);

        return new List<string>() { "Hawaii", "Pepperoni", "Bolognaise" };
    }
}

I kept the WCF service very basic. It creates an instance of the DataCache object inside its constructor. This object offers an interface to the distributed cache. In order to create it, we must provide the addresses and network ports of the servers hosting the distributed cache.

public class PizzaService : IPizzaService
{
    private const string CacheServerName = "WIN-53K8O7PMTOP";
    private const int CacheServerPort = 22233;
    private const string CacheKey = "availablePizzas";

    private DataCache cache;
    private SlowRepository repository;

    public PizzaService()
    {
        // Setup AppFabric Cache
        List<DataCacheServerEndpoint> servers = new List<DataCacheServerEndpoint>();
        servers.Add(new DataCacheServerEndpoint(CacheServerName, CacheServerPort));

        DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();
        configuration.Servers = servers;

        //Set default properties for local cache (local cache disabled)
        configuration.LocalCacheProperties = new DataCacheLocalCacheProperties();
        configuration.SecurityProperties = 
            new DataCacheSecurity(DataCacheSecurityMode.None, DataCacheProtectionLevel.None);

        DataCacheFactory cacheFactory = new DataCacheFactory(configuration);
        this.cache = cacheFactory.GetCache("default"); // Get the default cache

        // Create our 'slow' repository
        this.repository = new SlowRepository();
    }

    public IEnumerable<string> GetAvailablePizzas()
    {
        IEnumerable<string> availablePizzas = null;

        // Try to get the item from the cache
        availablePizzas = (IEnumerable<string>)cache.Get(CacheKey);

        if (availablePizzas != null)
            return availablePizzas;
        else
        {
            availablePizzas = repository.GetPizzas();

            // Store data in the cache
            cache.Put(CacheKey, availablePizzas);

            return availablePizzas;
        }
    }
}

If you call the service twice, you will notice that the second time the data is taken from the cache instead of from the repository. If we restart the web service, the data is still taken from the cache. If we execute the PowerShell command “Get-CacheStatistics” we can see that the cache contains our data.

powershell_cachestatistics

About these ads
Categories: C#, WCF
  1. August 30, 2012 at 11:03

    thank you, and +1 for the Get-CacheStatistics command.

  2. September 2, 2012 at 22:41

    @ügyvitel: yes…and MS should make better MSDN pages about them.

  3. thien
    December 5, 2012 at 09:50

    Can i have sour code of this sample?

    Thanks
    Thien Nguyen

  4. Tom
    January 16, 2013 at 03:30

    look how easy is add appfabric cache to a service with this product http://www.youtube.com/watch?v=05aDw_hcUBI

  1. August 30, 2012 at 09:32

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 26 other followers

%d bloggers like this: