Wednesday, August 5, 2020

Azure - Event Hubs - Send Event Messages



Navigate to the eventhub namespace shared access policy.



And on the right hand side copy the primary connection string.



Then goto the codebase and paste the copied connection string.



Next go back to the azure portal and copy the event hub name.



Goto the codebase and paste the eventhub name.



The codebase is listed below for reference.

using System;
using System.Text;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Producer;

namespace EventHubMessageSender
{
    class Program
    {
        static async Task Main()
        {
            string connectionString = "Endpoint=sb://eh-dataengg.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=dVqBZs0nACcKaS1NnOiHXjl6numsGCDFN8/Plxqcjvs=";
            string eventHubName = "eh1";

            // Create a producer client that you can use to send events to an event hub
            await using (var producerClient = new EventHubProducerClient(connectionString, eventHubName))
            {
                // Create a batch of events
                using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();

                // Add events to the batch. An event is a represented by a collection of bytes and metadata.
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("First event")));
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Second event")));
                eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes("Third event")));

                // Use the producer client to send the batch of events to the event hub
                await producerClient.SendAsync(eventBatch);
                Console.WriteLine("A batch of 3 events has been published.");
            }
        }
    }
}

Compile and run the code.
This should send events.

Goto eventhub 'eh1' in the Azure portal.
Before sending events the snapshot looks like this.



As soon as the code runs and the eventhub client gets created there is a spike in the incoming requests.



After sending the events, it looks like this.




and in the Azure portal.



Thus we can send messages to Azure event hub.

Cheers!





No comments:

Post a Comment