Azure

Azure Occasion Hub Implementation Utilizing .Internet Core Console App

Azure occasion hub is a knowledge streaming platform and ingesting occasion service. Occasion hub can obtain streaming information from one or a number of supply (occasion Producers) and it may be saved and processed by one or a number of customers. Occasion information might be captured/saved by the Azure Blob storage or Azure Knowledge Lake Storage for very long time processing functions. It may be built-in with Azure Stream Analytics and Azure Features from the occasion hub. 

 

A few of the necessary phrases which it is advisable perceive earlier than beginning Azure Occasion Hub implementation embrace: 

 

Occasion producer

 

Producers are accountable to generate the occasion information and ship to the occasion hub. One or a number of producers can ship information to the occasion hub.

 

Occasion receivers/ shopper

 

Customers are accountable to take heed to the occasion information from the supplied occasion hub. One or a number of customers can learn one partition or the entire occasion information from the occasion hub.

 

Client group

 

Occasion customers might be grouped primarily based on enterprise logic. Client shoppers want the knowledge of the group in an effort to learn occasion information from the occasion hub.

 

Partition

 

As information are despatched as  streaming information to the occasion hub, occasion hub makes use of partitions so that customers can learn one partition of the occasion information primarily based on partition id or can  learn all occasion information. Partition is immediately associated to the variety of customers who’re going to hear the occasion information.

 

Partition Key

 

Used to generate the hash key of the occasion information.

 

Extra particulars might be present in Azure documentation on the  Microsoft official web site.

 

The place to make use of:

  • Utility monitoring.
  • Irregular detection
  • Streaming information captured and evaluation.

Some real-world purposes which can be utilized with Azure Occasion Hub

 

Studying sensor information

 

There’s an Automated Visitors System has been put in within the metropolis.  The appliance data the visitors information in actual time with its camaras and sensors. In a traditional state of affairs an computerized visitors system works as per schedule but when there may be some irregular state of affairs like a visitors jam or pure disasters it ought to have the ability to deal with this by some computerized mechanism to redirect street visitors to different routes. Additionally, the system ought to have the ability to alert the visitors police to deal with the state of affairs. As sensors generate big information from totally different sources from everywhere in the metropolis (a number of occasion sources) on the similar time (could also be 10 million or extra per sec) a traditional system shall be not in a position to in a position to seize all of the occasions.

 

Right here Azure Occasion Hub can ingest all streaming information coming from all of the visitors sign facilities (metropolis squares) analyze it primarily based on which determination must be taken by Automated Visitors System. So, on this case, the actual time information shall be captured by sensors from the automated visitors system and people information are ship to the Azure occasion hub for information storage and evaluation primarily based on which system can decide.

 

Ecommerce software to captures person information for reinforcing ecommerce enterprise

 

Ecommerce purposes seize person information like person id, cellular no, system identification, location, gadgets which person have searched & person desire, primarily based on which product promotion might be set on person notification space and in addition might be exhibited to his social websites commercial space. Person can entry eCommerce purposes from totally different system like cellular, desktop, laptop computer and tab and so forth. It should have the ability to seize all person information in actual time. Once more, Azure Occasion Hub can seize all occasion information and might save and go the information to the opposite programs for evaluation primarily based on which product promotion might be despatched to particular person person’s units.

 

These days, purposes are  not solely supposed to have the ability to execute enterprise logic correctly (like buy requests) however additionally they should have the ability to lead the enterprise to the following stage and supply data primarily based on which purposes can predict & counsel gadgets which a person goes to purchase sooner or later from ecommerce platforms.

 

Here’s what we’re going to study:

 

Azure occasion hub implementation utilizing .web core console software.

 

We’re going to take ecommerce purposes on this demonstration.

 

 

create Occasion Hub in Azure

 

So as to create occasion, first occasion hub namespace is required.

  • Login to the Azure portal and navigate to the Azure Occasion Hub.
  • Now click on on add button to create namespace.

    Azure Event Hub Implementation Using .Net Core Console App

  • The remainder of the configuration might be carried out with default setting. Now assessment and create namespace.

    Azure Event Hub Implementation Using .Net Core Console App

As soon as Occasion Hub namespace is created, now we will proceed with occasion hub creation. Navigate to the newly create Occasion Hub namespace and click on on namespace.

 

Click on on Occasion Hub and supply the obligatory fields. As we’re utilizing primary tier possibility in occasion hub namespace, some choices shall be in disabled mode.

 

Azure Event Hub Implementation Using .Net Core Console App

 

Seize possibility can’t be configured as it isn’t obtainable in primary tier plan. Partition rely is a crucial property and it’s immediately associated to the occasion customers. On this demo we’re implementing two customers to hear the occasion hub.

 

After creating the namespace and the occasion hub we have to create SAS(Shared entry insurance policies) to entry the occasion hub occasion from our console software.

 

There are Three claims in shared entry coverage. One coverage can have all three choices or could also be a mixture of any two. However per the appliance wants, I counsel you create coverage primarily based on tasks.

 

SAS claims

For this demo, two insurance policies have been created, one for producers with ship declare and one for customers with hear declare. Please be aware that insurance policies might be outlined in Occasion Hub Occasion stage and Occasion namespace stage as properly. On this demo, insurance policies are outlined in occasion namespace stage.

 

Azure Event Hub Implementation Using .Net Core Console App

 

On this instance, I shall be protecting the occasion producer and occasion customers solely. I’ve used .web core 3.1 with Visual Studio 2019. It’s at all times a great apply to implement code with the  newest model.

 

We’re going to implement an ecommerce software which collects person information from person units and sends it to an occasion hub. Person information accommodates person information, system information and the gadgets which the person desires to purchase within the close to future, and he’s trying to find that merchandise in ecommerce purposes. Now we have created two customers who’re going to take heed to the occasion hub and devour the occasion information. Occasion information might be additional handed to any evaluation software to generate the enterprise lead.

 

There are Three components within the console software.

 

Entry level or foremost methodology

 

Code from Program.cs,

  1. utilizing System;  
  2. utilizing System.Threading;  
  3. utilizing System.Threading.Duties;  
  4. namespace AzureEventHubMutliProducerConsumer {  
  5.     class Program {  
  6.         static void Fundamental(string[] args) {  
  7.             Program program = new Program();  
  8.             Process[] duties = new Process[3];  
  9.             duties[0] = Process.Run(() => {  
  10.                 Thread.Sleep(1000);  
  11.                   
  12.                 program.RunProducer();  
  13.             });  
  14.             duties[1] = Process.Run(() => {  
  15.                 Thread.Sleep(1000);  
  16.                   
  17.                 program.RunEventHubConsumerReadEvent();  
  18.             });  
  19.             duties[2] = Process.Run(() => {  
  20.                 Thread.Sleep(1000);  
  21.                   
  22.                 program.RunEventHubConsumerReadEventPartitionEvent();  
  23.             });  
  24.             Process.WaitAll(duties);  
  25.             Console.WriteLine(“Press any any to finish program”);  
  26.             Console.ReadKey();  
  27.         }  
  28.         public void RunProducer() {  
  29.               
  30.             EventProducer eventProducer = new EventProducer();  
  31.             eventProducer.Init();  
  32.             eventProducer.CreatePurchaseRequest().Wait();  
  33.         }  
  34.         public void RunEventHubConsumerReadEvent() {  
  35.               
  36.             EventHubConsumerClientDemo eventHubConsumer = new EventHubConsumerClientDemo();  
  37.             eventHubConsumer.ConsumerReadEvent(“$Default”).Wait();  
  38.         }  
  39.         public void RunEventHubConsumerReadEventPartitionEvent() {  
  40.               
  41.             EventHubConsumerClientDemo eventHubConsumer = new EventHubConsumerClientDemo();  
  42.             eventHubConsumer.ConsumerReadEventPartitionEvent(“$Default”“1”).Wait();  
  43.         }  
  44.     }  
  45. }  

Three threads shall be created by the console program in an effort to run occasion producer and two customers can run in parallel.

 

Occasion Producer

 

Code for EventProducer.cs

  1. utilizing System;  
  2. utilizing System.Collections.Generic;  
  3. utilizing System.Textual content;  
  4. utilizing System.Threading.Duties;  
  5. utilizing Azure.Messaging.EventHubs;  
  6. utilizing Azure.Messaging.EventHubs.Producer;  
  7. namespace AzureEventHubMutliProducerConsumer {  
  8.     public class EventProducer {  
  9.         string connectionString = “—- Get key from azure queue ->Shared entry key—”;  
  10.         string eventHubName = “—-Occasion hub name–“;  
  11.         EventDataBatch generateData;  
  12.         Record < string > system = new Record < string > ();  
  13.         EventHubProducerClient producerClient;  
  14.         public void Init() {  
  15.             producerClient = new EventHubProducerClient(connectionString, eventHubName);  
  16.             system.Add(“Cellular”);  
  17.             system.Add(“Laptop computer”);  
  18.             system.Add(“Desktop”);  
  19.             system.Add(“Pill”);  
  20.         }  
  21.         public async Process GenerateEvent() {  
  22.             attempt {  
  23.                   
  24.                 int partitionId = 0;  
  25.                 foreach(var eachDevice in system) {  
  26.                     StringBuilder strBuilder = new StringBuilder();  
  27.                     var batchOptions = new CreateBatchOptions() {  
  28.                         PartitionId = partitionId.ToString()  
  29.                     };  
  30.                     generateData = producerClient.CreateBatchAsync(batchOptions).Outcome;  
  31.                     strBuilder.AppendFormat(“Search triggered for iPhone 21 from decive {0} “, eachDevice);  
  32.                     var eveData = new EventData(Encoding.UTF8.GetBytes(strBuilder.ToString()));  
  33.                       
  34.                     eveData.Properties.Add(“UserId”“UserId”);  
  35.                     eveData.Properties.Add(“Location”“North India”);  
  36.                     eveData.Properties.Add(“DeviceType”, eachDevice);  
  37.                     generateData.TryAdd(eveData);  
  38.                     producerClient.SendAsync(generateData).Wait();  
  39.                       
  40.                     partitionId++;  
  41.                     if (partitionId > 1) partitionId = 0;  
  42.                 }  
  43.                 await Process.CompletedTask;  
  44.             } catch (Exception exp) {  
  45.                 Console.WriteLine(“Error occruied {0}. Strive once more later”, exp.Message);  
  46.             }  
  47.         }  
  48.     }  
  49. }  

Init() methodology will initialize EventHubProducer consumer with occasion connection key and occasion hub identify. It would additionally create and add four units to the system listing. In the actual world, there is likely to be the thousands and thousands of the units and thousands and thousands of customers utilizing ecommerce on the similar time. We are attempting to duplicate the identical situation through the use of the system listing to generate occasions.

 

GenerateEvent() methodology will generate occasion information for every system with some person information. We’re utilizing the partition id Zero or 1 which shall be utilized by the patron to learn occasion information primarily based on partition id. Occasion information might be despatched in a single occasion information or a batch of occasion information, right here we’re sending batch with partition id.

 

Occasion Client

 

Code for EventConsumer.cs

  1. utilizing Azure.Messaging.EventHubs.Client;  
  2. utilizing System;  
  3. utilizing System.Textual content;  
  4. utilizing System.Threading;  
  5. utilizing System.Threading.Duties;  
  6. namespace AzureEventHubMutliProducerConsumer {  
  7.     public class EventHubConsumerClientDemo {  
  8.         string connectionString = “—- Get key from azure queue ->Shared entry key—”;  
  9.         string eventHubName = “—-Occasion hub name–“;  
  10.           
  11.         public async Process ConsumerReadEvent(string consumerGroup) {  
  12.             attempt {  
  13.                 CancellationTokenSource cancellationSource = new CancellationTokenSource();  
  14.                 cancellationSource.CancelAfter(TimeSpan.FromSeconds(30));  
  15.                 EventHubConsumerClient eventConsumer = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);  
  16.                 await foreach(PartitionEvent partitionEvent in eventConsumer.ReadEventsAsync(cancellationSource.Token)) {  
  17.                     Console.WriteLine(“—Execution from ConsumerReadEvent method—“);  
  18.                     Console.WriteLine(“——“);  
  19.                     Console.WriteLine(“Occasion Knowledge recieved {0} “, Encoding.UTF8.GetString(partitionEvent.Knowledge.Physique.ToArray()));  
  20.                     if (partitionEvent.Knowledge != null) {  
  21.                         Console.WriteLine(“Occasion Knowledge {0} “, Encoding.UTF8.GetString(partitionEvent.Knowledge.Physique.ToArray()));  
  22.                         if (partitionEvent.Knowledge.Properties != null) {  
  23.                             foreach(var keyValue in partitionEvent.Knowledge.Properties) {  
  24.                                 Console.WriteLine(“Occasion information key = {0}, Occasion information worth = {1}”, keyValue.Key, keyValue.Worth);  
  25.                             }  
  26.                         }  
  27.                     }  
  28.                 }  
  29.                 Console.WriteLine(“ConsumerReadEvent finish”);  
  30.                 await Process.CompletedTask;  
  31.             } catch (Exception exp) {  
  32.                 Console.WriteLine(“Error occruied {0}. Strive once more later”, exp.Message);  
  33.             }  
  34.         }  
  35.           
  36.         public async Process ConsumerReadEventPartitionEvent(string consumerGroup, string partitionId) {  
  37.             attempt {  
  38.                 CancellationTokenSource cancellationSource = new CancellationTokenSource();  
  39.                 cancellationSource.CancelAfter(TimeSpan.FromSeconds(30));  
  40.                 EventHubConsumerClient eventConsumer = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);  
  41.                 ReadEventOptions readEventOptions = new ReadEventOptions() {  
  42.                     MaximumWaitTime = TimeSpan.FromSeconds(30)  
  43.                 };  
  44.                 await foreach(PartitionEvent partitionEvent in eventConsumer.ReadEventsFromPartitionAsync(partitionId, EventPosition.Newest, readEventOptions, cancellationSource.Token)) {  
  45.                     Console.WriteLine(“—Execution from ConsumerReadEventPartitionEvent method—“);  
  46.                     Console.WriteLine(“——“);  
  47.                     if (partitionEvent.Knowledge != null) {  
  48.                         Console.WriteLine(“Occasion Knowledge recieved {0} “, Encoding.UTF8.GetString(partitionEvent.Knowledge.Physique.ToArray()));  
  49.                         if (partitionEvent.Knowledge.Properties != null) {  
  50.                             foreach(var keyValue in partitionEvent.Knowledge.Properties) {  
  51.                                 Console.WriteLine(“Occasion information key = {0}, Occasion information worth = {1}”, keyValue.Key, keyValue.Worth);  
  52.                             }  
  53.                         }  
  54.                     }  
  55.                 }  
  56.                 await Process.CompletedTask;  
  57.             } catch (Exception exp) {  
  58.                 Console.WriteLine(“Error occruied {0}. Strive once more later”, exp.Message);  
  59.             }  
  60.         }  
  61.     }  
  62. }  

Occasion shopper with ReadEventsAsync methodology

 

ConsumerReadEvent() methodology takes shopper group identify as  enter params and connects to the occasion hub with connection key and occasion hub identify. There’s a CancellationTokenSource used in order that after ready from supplied time interval for occasion information, it must be terminated routinely. Additionally, ReadEventOptions gives time interval. So as to learn occasion from even hub, EventHub- ConsumerClient has been used. The strategy ReadEventsAsync methodology will learn all of the occasion information from occasion hub.

  1. await foreach (PartitionEvent partitionEvent in eventConsumer.ReadEventsAsync(cancellationSource.Token))  

The remainder of the strategy is used to course of the occasion information and its properties and show in console. After consuming all occasion information from the occasion hub, shopper will watch for 30 seconds as supplied in cancellation token and after that the appliance will throw an exceptions and the appliance shall be terminated.

 

Occasion shopper with ReadEventsFromPartitionAsync methodology

 

It’s just like the ConsumerReadEvent methodology, however the principle distinction is the enter params and methodology which goes to learn occasion information by partition id. Whereas defining the partition within the Azure Occasion Hub namespace within the Azure portal we have now set solely 2 partitions, so solely Zero or 1 might be the partition id. Based mostly on the partition id supplied within the methodology, information shall be retrieved from occasion hub. The remainder of the partition shall be not consumed by the patron.

  1. await foreach (PartitionEvent partitionEvent in eventConsumer.ReadEventsFromPartitionAsync(partitionId, EventPosition.Newest, readEventOptions, cancellationSource.Token))  

EventPosition might be set to newest, early and another possibility as properly.

 

In abstract, we’re operating to 2 shopper shoppers in parallel. One will learn all occasion information and the opposite shopper will solely learn occasion information primarily based on partition id.

 

run purposes with this code

 

Possibility -1

 

Prerequisite- Visual Studio 2019 and .web core 3.1. Replace your “Shared entry key” in producer and shopper class

  • Open visible studio and click on on new -> challenge.
  • Choose .web core from left finish and choose the Console App(.web core) template.
  • Point out the trail the place resolution shall be created and click on one okay button.

    Azure Event Hub Implementation Using .Net Core Console App 

    New console app challenge shall be created with default Program.cs file.

    Now from Nuget bundle supervisor, search Azure.Messaging.EventHubs.Processor and set up for the chosen challenge.

    Azure Event Hub Implementation Using .Net Core Console App

  • Add new .cs file to the challenge and identify it as EventProducer.cs
  • Copy the content material from part “Code for EventProducer.cs” and paste in as EventProducer.cs file
  • Add new .cs file to the challenge and identify it as EventHubConsumerClientDemo.cs
  • Copy the content material from part “Code for EventHubConsumerClientDemo.cs” and paste in as EventHubConsumerClientDemo.cs file
  • Copy the content material of foremost entry level (solely c# code) and paste it within the Program.cs file.

Construct the answer and run the appliance.

 

Possibility -2

 

Obtain the zip file from right here and unzip in your native system. Open the answer file, construct the challenge, and run the appliance.

 

Thanks, and blissful coding ????

Show More

Related Articles

Leave a Reply

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

Back to top button