Configuring the .NET Core app to use Redis Cache on Azure

Once the cache is created, we can configure our .NET Core client application, probably an ASP.NET Core one, by adding a NuGet package as StackExchange.redis. Once the package is downloaded, we can use the Redis client API to use the Redis Cache that we have created on Azure.

To connect to the Redis Cache, we can add a namespace StackExchange, Redis, and create a connection class using ConnectionMultiplexer, as follows:

    ConnectionMultiplexer connection =    
ConnectionMultiplexer.Connect(
"myrediscache.redis.cache.windows.net:6380,
password=VOBP7q7Msw8bSy6+u0=,ssl=True,abortConnect=False");

ConnectionMultiplexer takes the connection string, which can be obtained from the Redis Cache on Azure by accessing the Access Keys option under Settings. The key benefit of ConnectionMultiplexer is that it recreates the connection automatically if connectivity is lost due to a network issue and is then resolved.

Once the connection is made, we can read the Redis Cache by calling the GetDatabase method of the connection object:

    IDatabase cache= connection.GetDatabase();

Finally, the values can be set or retrieved through the Set and Get methods from the cache object created earlier.

    cache.StringSet("UserName", "John"); 
cache.StringGet("UserName");

.NET objects can also be set to the cache, but they should have the serializable attribute annotated at the class level. For example, we can simply serialize the person object into the JSON format, and save it in the cache as follows:

    cache.StringSet("PersonObject",
JsonConvert.SerializeObject(personObj);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.62.168