Azure

How To Use Azure Redis Cache In C#

Introduction

Azure Redis Cache is predicated on open supply, in-memory Redis Cache that enables Internet apps to carry knowledge from a backend knowledge supply into cache and server Internet pages from the cache to enhance app efficiency. On this step-by-step tutorial, we are going to discover ways to use Azure Redis Cache in our Internet app.

What’s Azure Redis Cache?

Fashionable purposes principally work with a considerable amount of knowledge. On this state of affairs, if you retrieve knowledge from a database, it sometimes finds the desk and will get the outcomes that it sends again to the consumer. The efficiency, in such case, goes down as a consequence of a number of requests. So, to scale back some variety of requests, you should utilize cache knowledge that doesn’t change steadily.

Redis Cache is an open supply,in-memory database that’s used for enhancing the efficiency of an utility by retrieving and storing the information within the cache reminiscence utilizing a Key-value format.Azure Redis Cache is a feature-rich performance that offers you entry to safe, low-latency, high-performance throughput.

Let’s begin Redis Cache implementation with C#.

Step 1. Log into Azure port, go to Databases >> Redis Cache.

Step 2. Create a information Redis Cache.

Microsoft Azure Create-

Step 3. Get the Entry Keys to attach with the newly created Redis Cache.

Azure Redis Cache In C#

Set up the StackExchange.Redis

Step 4. Set up the StackExchange.Redis NuGet bundle utilizing the next command.

Set up-Package deal StackExchange.Redis

Stack Exchange Redis-

Let’s begin coding to retailer the information into Redis Cache and retrieve the information from Redis Cache. We had just lately seen the code of Azure Doc DB CRUD operations. If in case you have not learn it but, click on on Azure Doc DB CRUD Operation and browse. We’ve the code of CRUD operations in Doc DB. Now, we are going to implement Redis Cache right here.

Step 5. Just like the earlier article, we have to add Redis Cache connection string into the appsettings.dev.json file.

Schema-.jpg

Step 6. Now, add another property RedisCache into Config.cs that may get the worth of Redis Cache connection string from appsettings.dev.json.

public class Config
{
    public DocDbConnectionString docDb { get; set; }
    public string RedisCache { get; set; }
}`
public class DocDbConnectionString
{
    public string EndPoint { get; set; }
    public string AuthKey { get; set; }
    public string Database { get; set; }
    public string Assortment { get; set; }
}

Step 7. Let’s come to this system.cs file and add ConnectionMultiplexer for Redis Cache.

IDatabase cache = lazyConnection.Worth.GetDatabase();
non-public static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
    string cacheConnection = configs.RedisCache;
    return ConnectionMultiplexer.Join(cacheConnection);
});
public static ConnectionMultiplexer Connection
{
    get
    {
        return lazyConnection.Worth;
    }
}

Now, we are going to retailer a doc into Redis Cache on the idea of Key whereas making a doc into Doc DB and whereas studying this doc, we are going to use the Key to examine if the doc is current in Redis Cache or not. We’ll skip studying the doc farther from Doc DB. By doing this, we will enhance the efficiency of the applying.

var assortment = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Assortment);
attempt
{
    // create JObject which comprises the worker particulars
    Console.WriteLine("nCreating doc");
    JObject emp = new JObject();
    emp.Add("id", "V003");
    emp.Add("identify", "virendra");
    emp.Add("deal with", "Indore");
    emp.Add("Nation", "India");

    // create the doc into DocumentDb
    var createResponse = await Consumer.CreateDocumentAsync(assortment, emp);
    var createdDocument = createResponse.Useful resource;

    Console.WriteLine("Doc with id {0} created", createdDocument.Id);
    // Set JObject into redis cache with key "redisEmp3"
    var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());
    Console.WriteLine("Doc with key redisEmp3 saved into redis cache");
}
catch (Exception ex)
{
    throw ex;
}

Step 8. As an alternative, allow us to learn the doc from Redis Cache.

// Learn doc from Redis Cache.
var empInRedis = await cache.StringGetAsync("redisEmp3");
if (!empInRedis.IsNullOrEmpty)
{
    Console.WriteLine("Learn Doc from RedisCache {0} : ", empInRedis);
}

// If Redis Cache doesn't have Doc, then learn the doc from Doc DB
if (empInRedis.IsNullOrEmpty)
{
    var readResponse = await shopper.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Assortment, "V001"));
    var readDocument = readResponse.Useful resource;
    Console.WriteLine("Learn Doc {0}: ", readResponse.Useful resource.ToString());
}

The beneath snapshot reveals how we learn a doc from Redis Cache.

Azure Redis Cache 6-

Step 10. The next is the entire code of the Program.cs class.

utilizing System;
utilizing System.IO;
utilizing System.Threading.Duties;
utilizing Microsoft.Extensions.Configuration;
utilizing Newtonsoft.Json.Linq;
utilizing StackExchange.Redis;
utilizing Microsoft.Azure.Paperwork.Consumer;

public class Program
{
    non-public static IConfiguration Configuration { get; set; }
    non-public static Config configs;
    non-public DocumentClient shopper;
    non-public IDatabase cache = lazyConnection.Worth.GetDatabase();

    static void Primary(string[] args)
    {
        // Arrange Configuration
        var builder = new ConfigurationBuilder()
            .SetBasePath(Listing.GetCurrentDirectory())
            .AddJsonFile($"appsettings.{Atmosphere.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", non-compulsory: false, reloadOnChange: true);
        Configuration = builder.Construct();
        configs = new Config();
        Configuration.Bind(configs);

        Program obj = new Program();
        obj.CRUDOperation().Wait();
    }

    // CRUD Operation
    non-public async Activity CRUDOperation()
    {
        var assortment = UriFactory.CreateDocumentCollectionUri(configs.docDb.Database, configs.docDb.Assortment);
        attempt
        {
            // create JObject which comprises the worker particulars
            Console.WriteLine("nCreating doc");
            JObject emp = new JObject();
            emp.Add("id", "V003");
            emp.Add("identify", "virendra");
            emp.Add("deal with", "Indore");
            emp.Add("Nation", "India");
            // create the doc
            var createResponse = await Consumer.CreateDocumentAsync(assortment, emp);
            var createdDocument = createResponse.Useful resource;

            Console.WriteLine("Doc with id {0} created", createdDocument.Id);
            // Set JObject into redis cache with key "redisEmp3"
            var entryInRedis = await cache.StringSetAsync("redisEmp3", emp.ToString());
            Console.WriteLine("Doc with key redisEmp3 saved into redis cache");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        // learn doc from redis cache
        var empInRedis = await cache.StringGetAsync("redisEmp3");
        if (!empInRedis.IsNullOrEmpty)
        {
            Console.WriteLine("Learn Doc from RedisCache {0} : ", empInRedis);
        }
        if (empInRedis.IsNullOrEmpty)
        {
            // Learn doc from doc Db
            var readResponse = await shopper.ReadDocumentAsync(UriFactory.CreateDocumentUri(configs.docDb.Database, configs.docDb.Assortment, "V001"));
            var readDocument = readResponse.Useful resource;
            Console.WriteLine("Learn Doc {0}: ", readResponse.Useful resource.ToString());
        }

    }

    // Get a single occasion of Doc shopper and reuse
    public DocumentClient Consumer
    {
        get
        {
            if (shopper == null)
            {
                Uri endpointUri = new Uri(configs.docDb.EndPoint);
                shopper = new DocumentClient(endpointUri, configs.docDb.AuthKey, null, ConsistencyLevel.Session);
                shopper.OpenAsync();
            }
            return shopper;
        }
    }
    // To determine Redis Cache connection
    non-public static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
    {
        string cacheConnection = configs.RedisCache;
        return ConnectionMultiplexer.Join(cacheConnection);
    });

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

I hope this text will provide help to.

Know extra about our firm at Skrots. Know extra about our providers at Skrots Companies, Additionally checkout all different blogs at Weblog at Skrots

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button