Wednesday, June 2, 2021

  Using Azure Cache for Redis continued: 

Introduction: This article demonstrates a sample program to use the Azure Cache for Redis by setting and getting entries from the cache.

using System; 

using System.Linq; 

using System.Net.Sockets; 

using System.Threading; 

using Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime; 

using Microsoft.Azure.Management.Redis; 

using Microsoft.Azure.Services.AppAuthentication; 

using Microsoft.Extensions.Configuration; 

using Microsoft.Rest; 

using StackExchange.Redis; 

  

namespace RedisDriver 

{ 

    class Program 

    { 

        public static String subscriptionKey = ""; 

        public static String subscriptionId = ""; 

        public static String tenantId = ""; 

        public static String cachePrimary = ""; 

        public static String cacheLink = ""; 

        public static String resourceGroup = ""; 

        public static String region = ""; 

        public static String primaryAccessKey = ""; 

        public static String linkAccessKey = ""; 

        public static RedisManagementClient client; 

        private static IConfigurationRoot Configuration { get; set; } 

        private static long lastReconnectTicks = DateTimeOffset.MinValue.UtcTicks; 

        private static DateTimeOffset firstErrorTime = DateTimeOffset.MinValue; 

        private static DateTimeOffset previousErrorTime = DateTimeOffset.MinValue; 

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

        private static Lazy<ConnectionMultiplexerlazyConnection; 

  

        static async System.Threading.Tasks.Task Main(string[args) 

        { 

            IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); 

            IConfigurationRoot config = builder.Build(); 

            tenantId = config["tenantId"]; 

            subscriptionId = config["subscriptionId"]; 

            subscriptionKey = config["subscriptionKey"]; 

            resourceGroup = config["resourceGroupName"]; 

            cachePrimary = config["cachePrimary"]; 

            cacheLink = config["cacheLink"]; 

            primaryAccessKey = config["primaryAccessKey"]; 

            linkAccessKey = config["linkAccessKey"]; 

            region = config["region"]; 

            lazyConnection = CreateConnection(primaryAccessKey); 

            IDatabase cache = GetDatabase(); 

            WriteToCache(cache); 

            CloseConnection(lazyConnection); 

            //lazyConnection = CreateConnection(linkAccessKey); 

            //cache = GetDatabase(); 

            //WriteToCache(cache); 

            //CloseConnection(lazyConnection); 

  

        } 

        public static ConnectionMultiplexer Connection 

        { 

            get 

            { 

                return lazyConnection.Value; 

            } 

        } 

  

  

        private static Lazy<ConnectionMultiplexerCreateConnection(String accessKey) 

        { 

            return new Lazy<ConnectionMultiplexer>(() => 

            { 

                return ConnectionMultiplexer.Connect(accessKey); 

            }); 

        } 

  

        private static void CloseConnection(Lazy<ConnectionMultiplexeroldConnection) 

        { 

            if (oldConnection == null) 

                return; 

  

            try 

            { 

                oldConnection.Value.Close(); 

            } 

            catch (Exception) 

            { 

                // Example error condition: if accessing oldConnection.Value causes a connection attempt and that fails. 

            } 

        } 

        public static IDatabase GetDatabase() 

        { 

            return Connection.GetDatabase(); 

        } 

  

        public static System.Net.EndPoint[] GetEndPoints() 

        { 

            return Connection.GetEndPoints(); 

        } 

  

        public static IServer GetServer(string host, int port) 

        { 

            return Connection.GetServer(host, port); 

        } 

  

        protected static void WriteToCache(IDatabase cache) 

        { 

            var rand = new Random(); 

            for (int i = 1; i < 10; i++) 

            { 

                string payload = string.Join("", Enumerable.Repeat(0, 100).Select(n => (char)rand.Next(127))); 

                String key = payload.GetHashCode().ToString(); 

                cache.StringSet(key, payload); 

                String result = cache.StringGet(key).ToString(); 

                if (result.Equals(payload) == false) 

                { 

                    throw new Exception("Error in reading and writing to cache."); 

                } 

            } 

        } 

    } 

} 

 

No comments:

Post a Comment