Quickstart: Azure Event Hubs - Sending and Receiving Events

This guide will walk you through the essential steps to start using Azure Event Hubs. You'll learn how to create an Event Hubs namespace and an event hub, send events to it, and then receive those events using a simple consumer.

Prerequisites

Step 1: Create an Event Hubs Namespace and Event Hub

First, you need a place to store your events. This is done by creating an Event Hubs namespace, which acts as a container for one or more event hubs.

  1. Navigate to the Azure portal.
  2. Click Create a resource.
  3. Search for "Event Hubs" and select it. Click Create.
  4. Select your subscription and resource group, or create a new one.
  5. Enter a unique name for your namespace.
  6. Choose a location.
  7. Select a pricing tier (Basic is sufficient for this quickstart).
  8. Click Review + create, then Create.
  9. Once the namespace is deployed, navigate to it. Click + Event Hub.
  10. Enter a name for your event hub (e.g., my-event-hub).
  11. Leave the other settings at their defaults and click Create.

Step 2: Get Connection Strings

You'll need connection strings to authenticate your applications with Event Hubs. There are two primary connection strings:

  • RootManageSharedAccessKey: Provides full management access to the namespace.
  • Send and Listen policies: Specific permissions for sending or receiving.

For this quickstart, we'll use the root key.

  1. In your Event Hubs namespace page, click Shared access policies in the left menu.
  2. Click on the RootManageSharedAccessKey policy.
  3. Copy the Primary Connection String. Keep this secure!

It's a best practice to create more granular shared access policies with only the necessary permissions (e.g., send-only or listen-only) for your applications in production environments.

Step 3: Create a .NET Application

Let's create a simple .NET console application to send and receive events.

  1. Create a new directory for your project and navigate into it in your terminal.
  2. Create a new .NET console project: dotnet new console -n EventHubsQuickstart
  3. Change into the project directory: cd EventHubsQuickstart
  4. Add the Azure Event Hubs SDK package: dotnet add package Azure.Messaging.EventHubs

Step 4: Send Events

Replace the contents of your Program.cs file with the following code to send events:


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

// Replace with your actual Event Hub connection string and hub name
const string connectionString = "YOUR_EVENT_HUBS_CONNECTION_STRING";
const string eventHubName = "YOUR_EVENT_HUB_NAME";

await using var producerClient = new EventHubProducerClient(connectionString, eventHubName);

try
{
    // Create a batch of events
    using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();

    for (int i = 1; i <= 5; i++)
    {
        var eventData = new EventData(Encoding.UTF8.GetBytes($"Event {i} from my application."));
        if (!eventBatch.TryAddMessage(eventData))
        {
            // If the batch is full, send it and create a new one
            throw new Exception($"The batch has been fully loaded before the last message was added.");
        }
    }

    // Send the batch of events
    await producerClient.SendAsync(eventBatch);
    Console.WriteLine("A batch of 5 events has been sent.");
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
    // The client is disposable, so it's automatically disposed when exiting the scope.
    // If you want to explicitly dispose it, you can call producerClient.DisposeAsync();
}
                

Remember to replace YOUR_EVENT_HUBS_CONNECTION_STRING with your primary connection string and YOUR_EVENT_HUB_NAME with the name of your event hub.

Step 5: Receive Events

Now, let's modify Program.cs to also receive events. For simplicity, we'll run the sender and receiver in the same application. In a real-world scenario, these would typically be separate applications.

Important: You'll need to run the sending part first, then deploy this modified code. Alternatively, you can run two separate applications. For this quickstart, let's assume you'll run the sending code, then replace its contents with the following receiver code.

Replace the entire content of Program.cs with the following:


using Azure.Messaging.EventHubs;
using Azure.Messaging.EventHubs.Consumer;
using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;

// Replace with your actual Event Hub connection string and hub name
const string connectionString = "YOUR_EVENT_HUBS_CONNECTION_STRING";
const string eventHubName = "YOUR_EVENT_HUB_NAME";
const string consumerGroup = EventHubConsumerClient.DefaultConsumerGroupName; // Or a custom consumer group name

await using var consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName);

Console.WriteLine("Starting to listen for events...");

try
{
    await foreach (PartitionEvent partitionEvent in consumerClient.ReadEventsAsync())
    {
        Console.WriteLine($"Received event: '{Encoding.UTF8.GetString(partitionEvent.Data.EventBody.ToArray())}'");
        Console.WriteLine($"  Enqueued Time: {partitionEvent.Data.EnqueuedTime}");
        Console.WriteLine($"  Partition Id: {partitionEvent.Partition.Id}");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}
                

Remember to replace YOUR_EVENT_HUBS_CONNECTION_STRING and YOUR_EVENT_HUB_NAME again.

Step 6: Run the Application

  1. Open your terminal in the project directory.
  2. First, run the sending code (replace the `Program.cs` content with Step 4's code). dotnet run You should see "A batch of 5 events has been sent."
  3. Now, replace the `Program.cs` content with the receiving code (Step 5's code).
  4. Run the receiving code: dotnet run You should see the events you just sent being printed to the console.

The receiver needs to be running to consume events. If you run the receiver first, it won't have any events to process until the sender sends them.

Next Steps

Congratulations! You've successfully sent and received events using Azure Event Hubs. Here are some resources to explore further:

Continue to Setup