Azure redis Cache

Source: Internet
Author: User

The Azure shared cache service will be stopped on March 13, September 1, 2014, so you need to migrate to the azure redis cache before that date. Azure redis cache includes the following two levels of products.

    • Basic edition-single node, multiple specifications.
    • Standard Edition-Master/Slave Dual-node with multiple specifications. Standard-layer products will have 99.9% SLA.
    • For more information, see http://azure.microsoft.com/zh-cn/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/.

Use the stackexchange. redis nuget package to configure the cache Client

. NET applications developed with Visual Studio can be usedStackexchange. redisCache client to access the cache.

    1. To use the stackexchange. redis nuget package to configure client applications with Visual Studio, right-click the project in Solution Explorer and select Manage nuget packages ".
    2. In the online search text box, enterStackexchange. redisSelect it from the results and click "Install ".
    3. The nuget package downloads and adds the required assembly references to the client application to access the azure redis cache using the stackexchange. redis cache client.

Use the connectionmultiplexer class to connect to the cache

In azure redis cache, the cache connection is composedConnectionMultiplexerClass. To connect to the azure redis cache instance, call staticConnectionMultiplexer.ConnectMethod and pass it to the endpoint and key, as shown in the following.

ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("yhdcache0.redis.cache.windows.net,ssl=true,password=...");

ConnectionMultiplexerIt is designed to share and reuse the entire client application, so it does not need to be created every time you perform the operation. If the instance needs to be connected every time the cache is called after the instance is created, the performance will decrease.

Sharing in applicationsConnectionMultiplexerYou can use a static attribute to return the connected instance, as shown in the following figure. In this way, onceConnectionMultiplexerDisconnect to initialize a new connection instance.

Private Static connectionmultiplexer connection; Private Static connectionmultiplexer connection {get {If (connection = NULL |! Connection. isconnected) {connection = connectionmultiplexer. connect ("yhdcache0.redis.cache.windows.net, SSL = true, password =... ");} return connection;} if you do not want to use SSL to protect the communication between the cache and the client, you only need to pass it to the endpoint and the key, or setssl=false. For more information about advanced connection configuration options, see stackexchange. redis configuration model.ConnectionMultiplexer.GetDatabaseMethod to return a reference to the redis cache database. SlaveGetDatabaseThe object returned by the method is a lightweight pass-through object that 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 cachecache.StringSet("key1", "value");cache.StringSet("key2", 25);// Simple get of data types from the cachestring key1 = cache.StringGet("key1");int key2 = (int)cache.StringGet("key2");

 

Use the stackexchange. redis ClientRedisKeyAndRedisValueType to access and store projects in the cache. These types are mapped to most basic language types (includingstring), Usually not directly used. RedisStringsIs the most basic redis value type and can contain multiple data types (including serialized binary streams ). Although you may not use this type directlyString. Among them, the most common isStringSetAndStringGetMethod.

// Simple put of integral data types into the cachecache.StringSet("key1", "value");cache.StringSet("key2", 25);// Simple get of data types from the cachestring key1 = cache.StringGet("key1");int key2 = (int)cache.StringGet("key2");

Azure redis cache can use. Net objects and basic data types, but. Net objects can be cached only after they are serialized. This is the responsibility of application developers. In this way, developers can flexibly choose the serialization program. In the following exampleStackExchange.Redis.IDatabaseExtension class and binaryformatter to simplify the serialization of these objects.

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;        }    }}

RedisValueYou can use byte arrays directly.GetWhen the Helper Program method is used, it serializes the object into a byte stream and then caches the object. When a project is retrieved, the project is serialized as an object and then returned to the calling program.

ASP. NET session state application

  1. To use the redis cache session state nuget package to configure the client application in Visual Studio, right-click the project in Solution Explorer and select Manage nuget package ".
  2. In the online search text box, enterRedis cache session stateSelect it from the results and click "Install ".
    The nuget package downloads and adds the required Assembly reference, and adds the following parts to include ASP. web. config file to use the redis cache session Status 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>

Use the values in the azure Management Portal to preview the cache sidebar to configure these attributes, and then configure other values as needed.

  • host-Specify the cache endpoint.
  • port-Use your non-SSL port or SSL port, depending onssl.
  • accessKey-Use the cached CMK or CMK.
  • ssl-If you want to use SSL to protect the communication between the cache and client, set itTrueOtherwiseFalse. Be sure to specify the correctport.
  • throwOnError-If you want to throw an exception when a fault occurs, set itTrueIf you wantretryTimeoutInMillisecondsThe specified Retry Interval is setFalse.
  • retryTimeoutInMilliseconds-If you setthrowOnErrorIf this parameter is set to false, the system will retry the operation at this interval (in milliseconds.

 

MVC movie app with Azure redis cache in 15 minutes

Http://wacel.codeplex.com/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.