Redis Cache in Azure

Redis cache is open source Nosql based key value data sore approach  for faster query.

 

Redis in azure :

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 provides a thread-safe way to initialize only a single connected ConnectionMultiplexerinstance. In these examples abortConnect is set to false, which means that the call will succeed even if a connection to the Azure Redis Cache is not established. One key feature ofConnectionMultiplexer is that it will automatically restore connectivity to the cache once the network issue or other causes are resolved.

Copy
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
    return ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});

public static ConnectionMultiplexer Connection
{
    get
    {
        return lazyConnection.Value;
    }
}

For more information on advanced connection configuration options, see StackExchange.Redis configuration model.

To connect to the cache, your cache clients need the host name, ports, and keys. Some clients may refer to these items by slightly different names. To retrieve these items, browse to your cache in the Azure portal and click Settings or All settings.

Redis cache settings

Host name and ports

To access the host name and ports click Properties.

Redis cache properties

Access keys

To retrieve the access keys, click Access keys.

Redis cache access 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 GetDatabasemethod is a lightweight pass-through object and does not need to be stored.

Copy
// Connection refers to a property that returns a ConnectionMultiplexer
// as shown in the previous example.
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");

Now that you know how to connect to an Azure Redis Cache instance and return a reference to the cache database, let’s take a look at working with the cache.

Add and retrieve objects from the cache

Items can be stored in and retrieved from a cache by using the StringSet and StringGetmethods.

Copy
// If key1 exists, it is overwritten.
cache.StringSet("key1", "value1");

string value = cache.StringGet("key1");

Redis stores most data as Redis strings, but these strings can contain many types of data, including serialized binary data, which can be used when storing .NET objects in the cache.

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.

Copy
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.

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

Work with .NET objects in the cache

Azure Redis Cache can cache .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, and gives the developer flexibility in the choice of the serializer.

One simple way to serialize objects is to use the JsonConvert serialization methods inNewtonsoft.Json.NET and serialize to and from JSON. The following example shows a get and set using an Employee object instance.

Copy to clipboardCopy

Store ASP.NET page output in the cache

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

Azure Redis Cache Manage NuGet Packages

Type RedisOutputCacheProvider into the search text box, select it from the results, and clickInstall.

Azure Redis Cache Output Cache Provider

The Redis Output Cache Provider NuGet package has a dependency on the StackExchange.Redis.StrongName package. If the StackExchange.Redis.StrongName package is not present in your project it will be installed. Note that in addition to the strong-named StackExchange.Redis.StrongName package there is also the StackExchange.Redis non-strong-named version. If your project is using the non-strong-named StackExchange.Redis version you must uninstall it, either before or after installing the Redis Output Cache Provider NuGet package, otherwise you will get naming conflicts in your project. For more information about these packages, see Configure .NET cache clients.

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

Store ASP.NET session state in the cache

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

Type RedisSessionStateProvider into the search text box, select it from the results, and clickInstall.

Important:

If you are using the clustering feature from the premium tier, you must useRedisSessionStateProvider 2.0.1 or higher or an exception is thrown. This is a breaking change; for more information see v2.0.0 Breaking Change Details.

Azure Redis Cache Session State Provider

The Redis Session State Provider NuGet package has a dependency on the StackExchange.Redis.StrongName package. If the StackExchange.Redis.StrongName package is not present in your project it will be installed. Note that in addition to the strong-named StackExchange.Redis.StrongName package there is also the StackExchange.Redis non-strong-named version. If your project is using the non-strong-named StackExchange.Redis version you must uninstall it, either before or after installing the Redis Session State Provider NuGet package, otherwise you will get naming conflicts in your project. For more information about these packages, see Configure .NET cache clients.

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.

Copy
<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]
        databaseId = "0" [number]
        applicationName = "" [String]
        connectionTimeoutInMilliseconds = "5000" [number]
        operationTimeoutInMilliseconds = "5000" [number]
    />
    -->
    <add name="MySessionStateStore"type="Microsoft.Web.Redis.RedisSessionStateProvider"host="127.0.0.1"accessKey="" ssl="false"/>
    </providers>
</sessionState>

The commented section provides an example of the attributes and sample settings for each attribute.

Configure the attributes with the values from your cache blade in the Microsoft Azure Portal, and configure the other values as desired. For instructions on accessing your cache properties, see Configure Redis cache settings.

  • 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.
  • ssl – true if you want to secure cache/client communications with ssl; otherwise false. Be sure to specify the correct port.
    • The non-SSL port is disabled by default for new caches. Specify true for this setting to use the SSL port. For more information about enabling the non-SSL port, see the Access Portssection in the Configure a cache topic.
  • throwOnError – true if you want an exception to be thrown in the event of a failure, or false if you want the operation to fail silently. You can check for a failure by checking the static Microsoft.Web.Redis.RedisSessionStateProvider.LastException property. The default is true.
  • retryTimeoutInMilliseconds – Operations that fail are retried during this interval, specified in milliseconds. The first retry occurs after 20 milliseconds, and then retries occur every second until the retryTimeoutInMilliseconds interval expires. Immediately after this interval, the operation is retried one final time. If the operation still fails, the exception is thrown back to the caller, depending on the throwOnError setting. The default value is 0 which means no retries.
  • databaseId – Specifies which database to use for cache output data. If not specified, the default value of 0 is used.
  • applicationName – Keys are stored in redis as {<Application Name>_<Session ID>}_Data. This enables multiple applications to share the same key. This parameter is optional and if you do not provide it a default value is used.
  • connectionTimeoutInMilliseconds – This setting allows you to override the connectTimeout setting in the StackExchange.Redis client. If not specified, the default connectTimeout setting of 5000 is used. For more information, see StackExchange.Redis configuration model.
  • operationTimeoutInMilliseconds – This setting allows you to override the syncTimeout setting in the StackExchange.Redis client. If not specified, the default syncTimeout setting of 1000 is used. For more information, see StackExchange.Redis configuration model.

For more information about these properties, see the original blog post announcement atAnnouncing ASP.NET Session State Provider for Redis.

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

Copy
<!-- <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 instance.

 

<caching>
  <outputCachedefaultProvider="MyRedisOutputCache">
    <providers>
      <!--
      <add name="MyRedisOutputCache"
        host = "127.0.0.1" [String]
        port = "" [number]
        accessKey = "" [String]
        ssl = "false" [true|false]
        databaseId = "0" [number]
        applicationName = "" [String]
        connectionTimeoutInMilliseconds = "5000" [number]
        operationTimeoutInMilliseconds = "5000" [number]
      />
      -->
      <add name="MyRedisOutputCache"type="Microsoft.Web.Redis.RedisOutputCacheProvider"host="127.0.0.1"accessKey="" ssl="false"/>
    </providers>
  </outputCache>
</caching>
class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }

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

// Store to cache
cache.StringSet("e25", JsonConvert.SerializeObject(new Employee(25, "Clayton Gragg")));

// Retrieve from cache
Employee e25 = JsonConvert.DeserializeObject<Employee>(cache.StringGet("e25"));

You Might Also Like

Leave a Reply