Export (0) Print
Expand All

Migrate from Shared Caching to Azure Redis Cache (Preview)

Updated: June 19, 2014

Migrating your applications that use Microsoft Azure Shared Caching to Azure Redis Cache (Preview) can be accomplished with minimal changes to your application. While the APIs are not exactly the same; they are similar, and much of your existing code that uses Shared Caching to access a cache can be reused with minimal changes. This topic shows how to make the necessary configuration and application changes to migrate your Shared Caching applications to use Azure Redis Cache (Preview).

noteNote
Azure Shared Cache goes out of service September 1, 2014, so you will need to move to Azure Redis Cache (Preview) or Managed Cache Service by that date. We recommend moving to Azure Redis Cache (Preview) but if you want to move your application with no code changes you can move to Managed Cache Service. This topic covers migrating to Azure Redis Cache (Preview); for guidance on migrating to Managed Cache Service, see Migrate from Shared Caching to Azure Managed Cache Service.

Azure Redis Cache (Preview) is available in the following two tiers.

  • Basic – single node, multiple sizes.

  • Standard – Two node Master/Slave, multiple sizes. Once the preview period is over, the standard tier offering will have a 99.9% SLA.

noteNote
During the preview period, Azure Redis Cache (Preview) will be available in the 250 MB and 1 GB sizes. For a limited time the cache will be offered free, with a limit of two caches per subscription. For more information, see Azure Redis Cache (preview) pricing.

A starting point for migration is to pick the size that matches your existing Shared Caching offering, and then scale up or down depending on the requirements of your application.

  1. Caches in Azure Redis Cache (Preview) are created and managed in the Azure Management Portal Preview. To create a cache in Azure Redis Cache (Preview), log into the Azure Management Portal Preview.

    noteNote
    To use Azure Redis Cache (Preview), you need an Azure account. If you don’t have one, you can create a free trial account in just a couple of minutes. For details, see Azure Free Trial.

  2. In the Azure Management Portal Preview, click New, Cache.

    Azure Redis Cache New Cache Menu
  3. In the New Redis Cache (Preview) blade, specify the desired configuration for the cache.

    Azure Redis Cache New Redis Cache Blade
    • In Dns name, enter a subdomain name to use for the cache endpoint. The endpoint must be a string between six and twenty characters, contain only lowercase numbers and letters, and must start with a letter.

    • Use Pricing Tier to select the desired cache size and features. Azure Redis Cache (Preview) is available in the following two tiers.

      • Basic – single node, multiple sizes.

      • Standard – Two node Master/Slave, multiple sizes. Once the preview period is over, the standard tier offering will have a 99.9% SLA.

      noteNote
      During the preview period, Azure Redis Cache (Preview) will be available in the 250 MB and 1 GB sizes. For a limited time the cache will be offered free, with a limit of two caches per subscription. For more information, seeAzure Redis Cache (preview) pricing.

    • For Subscription, select the Azure subscription that you want to use for the cache.

    • In Resource group, select or create a resource group for your cache.

      noteNote
      For more information about resource groups, see Using Resource groups to manage your Azure resources.

    • Use Geolocation to specify the geographic location in which your cache is hosted. For the best performance, Microsoft strongly recommends that you create the cache in the same region as the cache client application.

  4. Once the new cache options are configured, click Create. It can take a few minutes for the cache to be created. To check the status, you can monitor the progress on the startboard. After the cache has been created, your new cache has a Running status and is ready for use with default settings.

    Azure Redis Cache New Cache Overview

Once the cache is created and configured, the next step is to remove the Shared Caching configuration, and add the add the Azure Redis Cache (Preview) configuration and references so that cache clients can access the cache.

To configure cache clients, perform the following steps for each cache client.

Before the client applications can be configured for Azure Redis Cache (Preview), the existing Shared Caching configuration and assembly references must be removed. If Shared Caching was configured using the Shared Caching NuGet package, then the configuration can be removed by uninstalling the Shared Caching NuGet package; otherwise it must be manually removed.

To uninstall the Shared Caching NuGet package, right-click the client project in Solution Explorer and choose Manage NuGet Packages. Select the Installed packages node, and type Caching into the Search installed packages box. Select Azure Shared Caching, click Uninstall, and then click Close.

Uninstall Shared Caching NuGet Package
noteNote
If there is no Microsoft Azure Shared Caching NuGet package in the list, then click Close and follow the steps in Manually remove the Shared Caching configuration.

Uninstalling the Shared Caching NuGet package removes the Shared Caching assemblies and the Shared Caching entries in the app.config or web.config of the client application. Because some customized settings may not be removed when uninstalling the NuGet package, open web.config or app.config and ensure that the following elements are completely removed.

  • Ensure that the dataCacheClients entry is removed from the configSections element. Do not remove the entire configSections element; just remove the dataCacheClients entry, if it is present.

    <configSections>
      <!-- Existing sections omitted for clarity. -->
      <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    
  • Ensure that the dataCacheClients section is removed. The dataCacheClients section will be similar to the following example.

    <dataCacheClients>
      <dataCacheClient name="default">
        <hosts>
          <host name="MyCacheNamespace.cache.windows.net" cachePort="22233" />
        </hosts>
    
        <securityProperties mode="Message">
          <messageSecurity 
            authorizationInfo="Your authorization token will be here.">
          </messageSecurity>
        </securityProperties>
      </dataCacheClient>
    </dataCacheClients>
    

Once the Shared Caching configuration is removed, you can configure the cache client as described in the following Configure a cache client using the StackExchange.Redis NuGet Package section.

To manually remove the Shared Caching configuration you must remove the Shared Caching assembly references and the Shared Caching configuration from app.config or web.config.

To remove the Shared Caching assembly references, select the cache client project in Solution Explorer and expand the References folder. For each of the assemblies in the following list, right-click the assembly in the References folder in Solution Explorer and choose Remove. If the client is a web project, also remove Microsoft.Web.DistributedCache.

  • Microsoft.ApplicationServer.Caching.Client

  • Microsoft.ApplicationServer.Caching.Core

  • Microsoft.WindowsFabric.Common

  • Microsoft.WindowsFabric.Data.Common

To remove the Shared Caching configuration, open the web.config or app.config of the cache client project and remove the following two items.

  • Remove the dataCacheClients entry from the configSections element. Do not remove the entire configSections element; just remove the dataCacheClients entry, if it is present.

    <configSections>
      <!-- Existing sections omitted for clarity. -->
      <section name="dataCacheClients" type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    
  • Remove the dataCacheClients section, which will be similar to the following example.

    <dataCacheClients>
      <dataCacheClient name="default">
        <hosts>
          <host name="MyCacheNamespace.cache.windows.net" cachePort="22233" />
        </hosts>
    
        <securityProperties mode="Message">
          <messageSecurity 
            authorizationInfo="Your authorization token will be here.">
          </messageSecurity>
        </securityProperties>
      </dataCacheClient>
    </dataCacheClients>
    

Once these items are removed, you can follow the steps in the next section to configure your cache client.

.NET applications developed in Visual Studio can use the StackExchange.Redis cache client to access their caches

noteNote
For more information about StackExchange.Redis, see the StackExchange.Redis github page and the StackExchange.Redis cache client documentation.

ImportantImportant
Before configuring the cache client using the StackExchange.Redis NuGet package, ensure that the Shared Caching configuration is completely removed from the web.config or app.config of the client project, as described in the previous section.

  1. To configure a client application in Visual Studio using the StackExchange.Redis NuGet package, right-click the project in Solution Explorer and choose Manage NuGet Packages.

    Azure Redis Cache Manage NuGet Packages
  2. Type StackExchange.Redis into the Search Online text box, select it from the results, and click Install.

    Azure Redis Cache StackExchange.Redis NuGet Packag
  3. The NuGet package downloads and adds the required assembly references for your client application to access Azure Redis Cache (Preview) with the StackExchange.Redis cache client.

The API for the StackExchange.Redis cache client is similar to the Shared Caching. This section provides an overview of the differences.

In Shared Caching, connections to the cache were handled by the DataCacheFactory and DataCache classes. In Azure Redis Cache (Preview), these connections are managed by the ConnectionMultiplexer class.

noteNote
Add the following using statement to the top of any file from which you want to access the cache.

using StackExchange.Redis;

If this namespace doesn’t resolve, be sure that you have configured your application for caching, as described in Configure .NET cache clients for Azure Redis Cache (Preview).

Note that the StackExchange.Redis client requires .NET Framework 4 or higher.

To connect to an Azure Redis Cache (Preview) instance, call the static ConnectionMultiplexer.Connect method and pass in the endpoint and key, as shown in the following example.

ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,ssl=true,password=...");
ImportantImportant
ConnectionMultiplexer is designed to be shared and reused throughout your client application, and does not need to be created on a per operation basis. If you create an instance and connect every time you make a call to the cache, performance will be degraded.

One approach to sharing a ConnectionMultiplexer instance in your application is to have a static property that returns a connected instance, similar to the following example. This way if the ConnectionMultiplexer ever becomes disconnected, a new connected instance can be initialized.

private static ConnectionMultiplexer connection;
private static ConnectionMultiplexer Connection 
{
    get
    {
        if(connection == null || !connection.IsConnected)
        {
            connection = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,ssl=true,password=...");
        }
        return connection;
    }
}

If you don’t want to secure your cache/client communication with SSL, simply pass in the endpoint and key, or set ssl=false.

ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,password=...");
noteNote
For more information about advanced connection configuration options, see StackExchange.Redis configuration model.

The cache endpoint, keys, and ports can be obtained from the Azure Management Portal Preview blade for your cache instance.

Azure Redis Cache Properties Azure Redis Cache Manage Keys

Once the connection is established, return a reference to the redis cache database by calling the ConnectionMultiplexer.GetDatabase method. The object returned from the GetDatabase method is a lightweight pass-through object and does not need to be stored.

IDatabase cache = Connection.GetDatabase();

// Perform cache operations using the cache object...
// Simple put of integral data types into the cache
cache.StringSet("key1", "value");
cache.StringSet("key2", 25);

// Simple get of data types from the cache
string key1 = cache.StringGet("key1");
int key2 = (int)cache.StringGet("key2");

The StackExchange.Redis client uses the RedisKey and RedisValue types for accessing and storing items in the cache. These types map onto most primitive language types, including string, and often are not used directly. Redis Strings are the most basic kind of Redis value, and can contain many types of data, including serialized binary streams,. and while you may not use the type directly, you will use methods that contain String in the name. The most common of these are the StringSet and StringGet methods.

noteNote
StringSet and StringGet are very similar to the Shared Caching Put and Get methods, with one major difference being that before you set and get a .NET object into the cache you must serialize it first. This is described in the following section, Work with .NET objects in the cache.

// Simple put of integral data types into the cache
cache.StringSet("key1", "value");
cache.StringSet("key2", 25);

// Simple get of data types from the cache
string key1 = cache.StringGet("key1");
int key2 = (int)cache.StringGet("key2");

Note that while you don’t have to do any casting when using string, you do when using int.

noteNote
Unless you are storing collections or other Redis data types in the cache, StringSet and StringGet are the methods to use, even if your value is not a string.

When calling StringGet, if the object exists, it is returned, and if it does not, null is returned. In this case you can retrieve the value from the desired data source and store it in the cache for subsequent use. This is known as the cache-aside pattern.

// Simple cache-aside pattern
string value = cache.StringGet("key1");
if (value == null)
{
    // The item keyed by "key1" is not in the cache. Obtain
    // it from the desired data source and add it to the cache.
    value = GetValueFromDataSource();

    cache.StringSet("key1", value);
}

To specify the expiration of an item in the cache, use the TimeSpan parameter of StringSet.

cache.StringSet("key1", "value1", TimeSpan.FromMinutes(90));

Azure Redis Cache (Preview) can work with .NET objects as well as primitive data types, but before a .NET object can be cached it must be serialized. This is the responsibility of the application developer. This gives the developer flexibility in the choice of the serializer. In the following examples, an extension class to the StackExchange.Redis.IDatabase type is used along with the BinaryFormatter to simplify the serialization of objects before they are cached.

public static class SampleStackExchangeRedisExtensions
{
    public static T Get<T>(this IDatabase cache, string key)
    {
        return Deserialize<T>(cache.StringGet(key));
    }

    public static object Get(this IDatabase cache, string key)
    {
        return Deserialize<object>(cache.StringGet(key));
    }

    public static void Set(this IDatabase cache, string key, object value)
    {
        cache.StringSet(key, Serialize(value));
    }

    static byte[] Serialize(object o)
    {
        if(o == null)
        {
            return null;
        }

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        using (MemoryStream memoryStream = new MemoryStream())
        {
            binaryFormatter.Serialize(memoryStream, o);
            byte[] objectDataAsStream = memoryStream.ToArray();
            return objectDataAsStream;
        }
    }

    static T Deserialize<T>(byte[] stream)
    {
        if(stream == null)
        {
            return default(T);
        }

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        using (MemoryStream memoryStream = new MemoryStream(stream))
        {
            T result = (T)binaryFormatter.Deserialize(memoryStream);
            return result;
        }
    }
}

The RedisValue type can work directly with byte arrays, so when the Get helper method is called, it serializes the object into a byte stream, which is then cached. When the item is retrieved, it is serialized back into an object, and returned to the caller.

In the following example, an instance of an Employee object is serialized.

[Serializable]
class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Employee(int EmployeeId, string Name)
    {
        this.Id = EmployeeId;
        this.Name = Name;
    }
}
IDatabase cache = Connection.GetDatabase();

// Put an Employee object into the cache
cache.Set("Employee25", new Employee(25, "Clayton Gragg"));

// Retrieve it
Employee e2 = cache.Get<Employee>("Employee25");

// Retrieve it as an object
Employee e3 = (Employee)cache.Get("Employee25");
WarningWarning
If your object is not serializable you will receive an exception similar to the following when you try to serialize it.

Type 'SampleApplication.Employee' in Assembly SampleApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

To migrate your application that stores ASP.NET session state, first remove the existing sessionState element from your web.config.

<sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
  <providers>
    <add name="AppFabricCacheSessionStoreProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" useBlobMode="true" dataCacheClientName="default" />
  </providers>
</sessionState>
noteNote
Before following the steps in this section, make sure that you have removed the Shared Caching configuration as described in Remove the Shared Caching Configuration. This step is required even if your application does not programmatically access the cache.

  1. To configure a client application in Visual Studio using the Redis Cache Session State NuGet package, right-click the project in Solution Explorer and choose Manage NuGet Packages.

    Azure Redis Cache Manage NuGet Packages
  2. Type Redis Cache Session State into the Search Online text box, select it from the results, and click Install.

    Azure Redis Cache Session State Provider
    The NuGet package downloads and adds the required assembly references and adds the following adds the following section into your web.config file that contains the required configuration for your ASP.NET application to use the Redis Cache Session State Provider.

      <sessionState mode="Custom" customProvider="MySessionStateStore">
          <providers>
            <!--
              <add name="MySessionStateStore" 
                host = "127.0.0.1" [String]
                port = "" [number]
                accessKey = "" [String]
                ssl = "false" [true|false]
                throwOnError = "true" [true|false]
                retryTimeoutInMilliseconds = "0" [number]
              />
            -->
            <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" />
          </providers>
        </sessionState>
    
    noteNote
    The commented section provides an example of the attributes and sample settings for each attribute.

  3. Configure the attributes with the values from your cache blade in the Azure Management Portal Preview, and configure the other values as desired.

    • host – specify your cache endpoint.

    • port – use either your non-SSL port or your SSL port, depending on the ssl settings.

    • accessKey – use either the primary or secondary key for your cache.

    • ssltrue if you want to secure cache/client communications with ssl; otherwise false. Be sure to specify the correct port.

    • throwOnErrortrue if you want an exception to be thrown in the event of a failure, or false if you want the operation retried using the retry interval specified by retryTimeoutInMilliseconds.

    • retryTimeoutInMilliseconds – if throwOnError is set to false, then operations will be retried using this interval, specified in milliseconds.

  4. Don’t forget to comment out the standard InProc session state provider section in your web.config.

    <!-- <sessionState mode="InProc" 
          customProvider="DefaultSessionProvider">
          <providers>
            <add name="DefaultSessionProvider" 
                  type="System.Web.Providers.DefaultSessionStateProvider, 
                        System.Web.Providers, Version=1.0.0.0, Culture=neutral, 
                        PublicKeyToken=31bf3856ad364e35" 
                  connectionStringName="DefaultConnection" />
          </providers>
      </sessionState> -->
    

Once these steps are performed, your application is configured to use the Redis Cache Session State Provider. When you use session state in your application, it will be stored in an Azure Redis Cache (Preview) instance.

See Also

Show:
© 2014 Microsoft