Tuesday, June 1, 2021

 Using Azure Cache for Redis: 

Introduction: This article demonstrates a sample program to use the Azure Cache for Redis with a linked server for replication which helps with high availability. 

Sample code: 

using System; 

using System.Collections.Generic; 

using System.Text; 

using Azure; 

using Azure.Identity; 

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

using Microsoft.Azure.Management.Redis; 

using Microsoft.Azure.Management.Redis.Models; 

using Microsoft.Azure.Management.ResourceManager; 

using Microsoft.Azure.Management.ResourceManager.Models; 

using Microsoft.Azure.Management.ServiceFabric; 

using Microsoft.Azure.Management.ServiceFabric.Models; 

using Microsoft.Azure.Services.AppAuthentication; 

using Microsoft.Extensions.Configuration; 

using Microsoft.IdentityModel.Clients.ActiveDirectory; 

using Microsoft.Rest; 

  

namespace Redis 

{ 

    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 RedisManagementClient client; 

  

        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"]; 

            region = config["region"]; 

  

  

            var credentials = new ApiKeyServiceClientCredentials(subscriptionKey); 

            var azureServiceTokenProvider = new AzureServiceTokenProvider(); 

            var token = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com", tenantId); 

            TokenCredentials tokenCredentials = new TokenCredentials(token); 

  

            client = new RedisManagementClient(tokenCredentials); 

            if (client == null) { throw new Exception("Unauthorized User."); } 

            client.SubscriptionId = subscriptionId; 

            RedisResource primaryResource = client.Redis.Get(resourceGroupcachePrimary); 

            if (primaryResource == null) { throw new Exception("Invalid parameter: " + cachePrimary); } 

  

            LinkResources(cachePrimarycacheLink); 

            // UnlinkResources(resourceGroupcachePrimarycacheLink); 

             

            RedisResource linkedResource = client.Redis.Get(resourceGroupcacheLink); 

            if (linkedResource == null) { throw new Exception("Invalid parameter: " + cacheLink); } 

            printResources(primaryResourcelinkedResource); 

        } 

        protected static void LinkResources(String cachePrimary, String cacheLink) 

        { 

            RedisResource primaryResource = client.Redis.Get(resourceGroupcachePrimary); 

            RedisLinkedServerCreateParameters redisLinkedServerCreateParameters = new RedisLinkedServerCreateParameters() 

            { 

                LinkedRedisCacheId = primaryResource.Id.Replace(cachePrimarycacheLink), 

                LinkedRedisCacheLocation = primaryResource.Location, 

                ServerRole = ReplicationRole.Secondary 

            }; 

            RedisLinkedServerWithProperties linked = client.LinkedServer.Create(resourceGroup, cachePrimary, cacheLink, redisLinkedServerCreateParameters); 

            if (linked == null) { throw new Exception("Invalid Parameter: " + cacheLink); } 

            Console.WriteLine("Id={linked.Id}"); 

            while (linked.ProvisioningState != "Succeeded") 

            { 

                Console.WriteLine("Not provisioned yet, sleeping 5 seconds ..."); 

                System.Threading.Thread.Sleep(5000); 

            } 

            Console.WriteLine("{" + linked.LinkedRedisCacheId + "} : provisioned at " + linked.LinkedRedisCacheLocation + " by name:" + linked.Name); 

        } 

        protected static void UnlinkResources(String resourceGroup, String cachePrimary, String cacheLink) 

        { 

            client.LinkedServer.Delete(resourceGroup, cachePrimary, cacheLink); 

        } 

        protected static void printResources(RedisResource primaryResource, RedisResource linkedResource) 

        { 

            List<RedisResource> resources = new List<RedisResource>(); 

            resources.Add(primaryResource); 

            resources.Add(linkedResource); 

            for (int i = 0; i < resources.Count; i++) 

            { 

                printResource(resources[i]); 

            } 

        } 

        protected static void printResource(RedisResource resource) 

        { 

            StringBuilder sb = new StringBuilder(); 

            sb.Append("------- BEGIN Resource Description --------\r\n"); 

            sb.Append("Name:     " + resource.Name + "\r\n"); 

            sb.Append("Id:       " + resource.Id + "\r\n"); 

            sb.Append("Count:    " + resource.LinkedServers.Count + "\r\n"); 

            sb.Append("RO:       " + resource.LinkedServers.IsReadOnly + "\r\n"); 

            sb.Append("Location: " + resource.Location + "\r\n"); 

            sb.Append("HostName: " + resource.HostName + "\r\n"); 

            sb.Append("State:    " + resource.ProvisioningState.ToString() + "\r\n"); 

            sb.Append("Shard#:   " + resource.ShardCount + "\r\n"); 

            if (resource.Zones != null) 

            { 

                sb.Append("Zones:    " + resource.Zones.ToString() + "\r\n"); 

                sb.Append("Zones#:   " + resource.Zones.Count + "\r\n"); 

            } 

            sb.Append("------- END Resource Description --------\r\n\n\n"); 

            Console.Write(sb.ToString()); 

        } 

        protected static void ManualFailover(RedisManagementClient client, String cachePrimary, String cacheLink) 

        { 

            RedisResource primaryResource = client.Redis.Get(resourceGroup, cachePrimary); 

            RedisResource linkedResource = client.Redis.Get(resourceGroup, cacheLink); 

            client.LinkedServer.Delete(resourceGroup, cachePrimary, cacheLink); 

            client.Redis.ExportData(resourceGroup, cacheLink, new ExportRDBParameters() { Container = "", Format = "", Prefix = "Failover: " }); 

            client.Redis.ForceReboot(resourceGroup, cacheLink, new RedisRebootParameters() { RebootType = RebootType.AllNodes, ShardId = 0 }); 

        } 

    } 

} 

 

No comments:

Post a Comment