Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / XML

AppFabric Caching Extension

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
2 Jan 2012CPOL4 min read 41.8K   1.2K   17   2
A component which can be plugged to a WCF service or any other client to utilize AppFabric caching features

Introduction

This component uses the Windows Server AppFabric Cache to provide distributed caching over servers and can be plugged into existing services/applications to directly use the AppFabric for caching. This component can be used for:

I. Caching outgoing WCF service responses - If the response message is in the cache, the custom channel immediately returns the response message from the cache without invoking the underlying service. This would not require any changes in the client implementation. At the service, a custom attribute is to be applied on the operation for which the response is to be cached.

II. Caching specific objects in the Business Layer to cache data retrieved from the data store (database or external services). It includes a CacheHelper class which currently supports:

  1. Helper methods to read and write from the AppFabric cache.
  2. An API that would return the encrypted key required to store data in the cache.
  3. An API to reset the time to live for an object which exists in the cache.

Installing and Configuring the AppFabric

There is no GUI for AppFabric. Powershell can be used for managing AppFabric. Make sure that the AppFabric cache service is running. You can determine whether the cache host is running by calling the Get-CacheHost command.

The following shows an example output from this command for a two-server cache cluster.

HostName : CachePort      Service Name            Service Status Version Info
--------------------      ------------            -------------- ------------
CacheServer1:22233        AppFabricCachingService UP             1 [1,1][1,1]
CacheServer2:22233        AppFabricCachingService UP             1 [1,1][1,1]

In this example, both CacheServer1 and CacheServer2 are running.

The next step is to create a named cache, a logical container used to store data. You do this through the New-Cache cmdlet in the Windows PowerShell:

New-Cache appFabricCache

View the Cache Configuration Settings

To view the current settings for the cache, use the Get-CacheConfig command.

Get-CacheConfig appFabricCache

In the previous example, the Get-CacheConfig command displays the cache configuration settings for Cache1. Here is an example of the output from this command:

CacheName            : appFabricCache
TimeToLive           : 10 mins
CacheType            : Partitioned
Secondaries          : 0
IsExpirable          : True
EvictionType         : LRU
NotificationsEnabled : False

Steps to Use this Component

  1. Add a reference to the Caching Extension library.
  2. You must update your application's web.config file as below:

AppFabric/WebConfig.png

The cache component is ready to be used. Below are the two different places where we would be leveraging this component:

C#
[CacheOperationBehavior(MinutesToCache = 5)] 
[OperationContract]
CustomerDC GetCustomer(string customerID);
  1. Apply the [CacheOperationBehavior] attribute to the operations you want to cache the responses for.
  2. For caching responses to the calls made to the database:
    C#
    //Read from Cache
    Customer custObj = (Customer)CacheHelper.Get(CUST_KEY);
    //If not present in cache
    if(custObj == null)
    {
            //Read from datastore
          custObj = ReadFromDataStore();
            //Populate Cache
         cacheHelper.Put(CUST_KEY ,custObj); 
          return custObj;
    }
    1. Define constants for a key and get the encrypted key using the GetEncryptedKey(string) API of the cache helper.
    2. Use Cache-aside pattern as shown below:

Implementation Details

To use AppFabric caching, the component requires the following libraries:

  • Microsoft.ApplicationServer.Caching.Core
  • Microsoft.ApplicationServer.Caching.Client

I. Caching Outgoing WCF Service Responses

The incoming call from the client is received through the Transport channel, and it passes through some channels before it reaches the Dispatcher. The Dispatcher associates the incoming call with the appropriate operation and then invokes it.

I have created a custom OperationInvoker to customize the behavior of invoking the data store.

How does it work?

AppFabric/Dispatcher.png

The key is generated using a combination of input parameters and the operation name. But as the parameters can be any number of objects, they are serialized into an XML string first.

It also has the TimeInMinutes property to indicate the lifetime of the cached object.

II. Caching Data that is Retrieved from the Data Store

Currently, the CacheHelper class exposes the following APIs:

  1. Get and put methods of the DataCache object.
  2. To reset the object timeout value - defining how long objects reside in the cache before expiring. The value specified for the object overrides the default settings for the cache.
  3. To create encrypted keys from a string.

Health Monitoring Tools

Performance Monitor

The AppFabric caching features install several Performance Monitor counters. For more information about the available counters, see Performance Counters for AppFabric Caching. You can observe or log some counter values to determine a baseline of typical cache cluster behavior. For example, in the AppFabric Caching:Cache category, you might observe that the Total Client Requests / sec value stays within general ranges that varies with the time of day.

Windows PowerShell

There are several Windows PowerShell commands that indicate the current status and the health of a cache cluster. This section demonstrates how to use the following commands:

  • Get-CacheHost
  • Get-CacheClusterHealth
  • Get-CacheStatistics

Resources

Download the Windows Server AppFabric from http://www.microsoft.com/download/en/details.aspx?id=15848.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAppFabric Caching for Web API Pin
isiddhant13-Jun-16 23:51
isiddhant13-Jun-16 23:51 
Hi

How to use AppFabric Caching for Web API, instead of wcf.
NewsGUI For App Fabric Pin
shahbaz_khan55511-Dec-13 22:30
shahbaz_khan55511-Dec-13 22:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.