Azure

Utilizing Azure Cache For Redis

Introduction

In at present’s article, we are going to check out utilizing Azure Cache for Redis. In our purposes, we frequently have to cache sure info to hurry up the efficiency. Now we have various choices to do that however most of them don’t scale very properly. On the Microsoft Cloud, we have now an amazing answer which is the Azure Cache for Redis. It offers us an answer to cache info for lookups, retailer session info, and many others. It is rather scalable, and we will scale it in keeping with our wants. In the present day, we are going to see how we will set it up in Microsoft Azure and use it in our .NET utility. So, allow us to start.

Creating the Azure Cache for Redis service in Microsoft Azure

Open the portal and comply with the next steps,

Seek for Azure Cache for Redis.

Using Azure Cache for Redis

Choose create and enter the under particulars.

Using Azure Cache for Redis

Using Azure Cache for Redis

Lastly, click on create to create the Redis Cache.

Using Azure Cache for Redis

As soon as created click on on the “Entry Keys” possibility as under.

Using Azure Cache for Redis

From right here choose and duplicate the Major connection string.

Creating the .NET utility to make use of this cache

Create a brand new console utility in Visual Studio 2022 group preview version.

Using Azure Cache for Redis

Using Azure Cache for Redis

Using Azure Cache for Redis

Using Azure Cache for Redis

We now have the appliance as under:

Using Azure Cache for Redis

Subsequent, add the required NuGet bundle (StackExchange.Redis)

Using Azure Cache for Redis

Using Azure Cache for Redis

Using Azure Cache for Redis

Using Azure Cache for Redis

Then add a brand new class that may maintain all of the Redis initialization and operational features.

Using Azure Cache for Redis

Additionally, add one other class “Worker” to show caching a category object.

Using Azure Cache for Redis

Lastly, allow us to add the NuGet bundle to serialize and de-serialize our worker class (Newtonsoft.Json).

Using Azure Cache for Redis

Using Azure Cache for Redis

Using Azure Cache for Redis

Now, add the under code to the “RedisInitializer.cs” class.

utilizing StackExchange.Redis;
utilizing System.Internet.Sockets;
namespace ConsoleAppAzureRedisCache {
    public static class RedisInitializer {
        public static Lazy < ConnectionMultiplexer > lazyConnection = CreateConnection();
        public static ConnectionMultiplexer Connection {
            get {
                return lazyConnection.Worth;
            }
        }
        public static Lazy < ConnectionMultiplexer > CreateConnection() {
            return new Lazy < ConnectionMultiplexer > (() => {
                return ConnectionMultiplexer.Join("<Insert Azure Cache for Redis connection string right here>");
            });
        }
        non-public static lengthy lastReconnectTicks = DateTimeOffset.MinValue.UtcTicks;
        non-public static DateTimeOffset firstErrorTime = DateTimeOffset.MinValue;
        non-public static DateTimeOffset previousErrorTime = DateTimeOffset.MinValue;
        non-public static readonly object reconnectLock = new object();
        public static TimeSpan ReconnectMinFrequency => TimeSpan.FromSeconds(60);
        public static TimeSpan ReconnectErrorThreshold => TimeSpan.FromSeconds(30);
        public static int RetryMaxAttempts => 5;
        public static void CloseConnection() {
            if (lazyConnection == null) return;
            attempt {
                lazyConnection.Worth.Shut();
            } catch (Exception) {}
        }
        public static void ForceReconnect() {
            var utcNow = DateTimeOffset.UtcNow;
            lengthy previousTicks = Interlocked.Learn(ref lastReconnectTicks);
            var previousReconnectTime = new DateTimeOffset(previousTicks, TimeSpan.Zero);
            TimeSpan elapsedSinceLastReconnect = utcNow - previousReconnectTime;
            if (elapsedSinceLastReconnect < ReconnectMinFrequency) return;
            lock(reconnectLock) {
                utcNow = DateTimeOffset.UtcNow;
                elapsedSinceLastReconnect = utcNow - previousReconnectTime;
                if (firstErrorTime == DateTimeOffset.MinValue) {
                    firstErrorTime = utcNow;
                    previousErrorTime = utcNow;
                    return;
                }
                if (elapsedSinceLastReconnect < ReconnectMinFrequency) return;
                TimeSpan elapsedSinceFirstError = utcNow - firstErrorTime;
                TimeSpan elapsedSinceMostRecentError = utcNow - previousErrorTime;
                bool shouldReconnect = elapsedSinceFirstError >= ReconnectErrorThreshold && elapsedSinceMostRecentError <= ReconnectErrorThreshold;
                previousErrorTime = utcNow;
                if (!shouldReconnect) return;
                firstErrorTime = DateTimeOffset.MinValue;
                previousErrorTime = DateTimeOffset.MinValue;
                Lazy < ConnectionMultiplexer > oldConnection = lazyConnection;
                CloseConnection();
                lazyConnection = CreateConnection();
                Interlocked.Change(ref lastReconnectTicks, utcNow.UtcTicks);
            }
        }
        non-public static T BasicRetry < T > (Func < T > func) {
            int reconnectRetry = 0;
            int disposedRetry = 0;
            whereas (true) {
                attempt {
                    return func();
                } catch (Exception ex) when(ex is RedisConnectionException || ex is SocketException) {
                    reconnectRetry++;
                    if (reconnectRetry > RetryMaxAttempts) throw;
                    ForceReconnect();
                }
                catch (ObjectDisposedException) {
                    disposedRetry++;
                    if (disposedRetry > RetryMaxAttempts) throw;
                }
            }
        }
        public static IDatabase GetDatabase() {
            return BasicRetry(() => Connection.GetDatabase());
        }
        public static System.Internet.EndPoint[] GetEndPoints() {
            return BasicRetry(() => Connection.GetEndPoints());
        }
        public static IServer GetServer(string host, int port) {
            return BasicRetry(() => Connection.GetServer(host, port));
        }
    }
}

Add the under code to the “Worker.cs” class

namespace ConsoleAppAzureRedisCache {
    public class Worker {
        public int Id {
            get;
            set;
        }
        public string ? Identify {
            get;
            set;
        }
        public int Age {
            get;
            set;
        }
    }
}

Lastly, add the under code to the “Program.cs” file

utilizing StackExchange.Redis;
utilizing ConsoleAppAzureRedisCache;
utilizing Newtonsoft.Json;
IDatabase cache = RedisInitializer.GetDatabase();
string cacheCommand = "PING";
Console.WriteLine("nCache command  : " + cacheCommand);
Console.WriteLine("Cache response : " + cache.Execute(cacheCommand).ToString());
cacheCommand = "SET Message "This worth has been set from the .NET app!"";
Console.WriteLine("nCache command  : " + cacheCommand);
Console.WriteLine("Cache response : " + cache.StringSet("Message", "This worth has been set from the .NET app!").ToString());
cacheCommand = "GET Message";
Console.WriteLine("nCache command  : " + cacheCommand);
Console.WriteLine("Cache response : " + cache.StringGet("Message").ToString());
var worker = new Worker {
    Id = 1, Identify = "John Doe", Age = 25
};
var empValue = JsonConvert.SerializeObject(worker);
Console.WriteLine("Cache response : " + cache.StringSet("Worker", empValue));
Console.WriteLine("Cache response : " + cache.StringGet("Worker").ToString());
var employeeFromCache = JsonConvert.DeserializeObject < Worker > (cache.StringGet("Worker").ToString());
Console.WriteLine($ "Worker from Cache particulars - Id: {employeeFromCache?.Id}, Identify:{employeeFromCache?.Identify}, Age: {employeeFromCache?.Age}");
RedisInitializer.CloseConnection();

Now, we are going to compile and run our utility and see the under output.

Using Azure Cache for Redis

Therefore, we see how simple it’s to setup the Cache and use it in our .NET purposes. We simply have to embed the connection string and we’re able to go.

Abstract

On this article, we took a have a look at the Azure Cache for Redis function. We noticed how we set it up and use it from our .NET utility. It’s a very scalable and safe answer for our caching and session storage necessities. Completely satisfied coding!

Show More

Related Articles

Leave a Reply

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

Back to top button