Azure Event Hubs: Sending Events to a Hub

This tutorial will guide you through the process of sending events to an Azure Event Hub using the Azure SDK for your preferred programming language. Event Hubs is a highly scalable data streaming platform and event ingestion service.

Prerequisites

Steps

Step 1: Install the Azure Event Hubs SDK

First, you need to install the appropriate Azure Event Hubs client library for your development environment.

Node.js

npm install @azure/event-hubs

Python

pip install azure-eventhubs

C#

dotnet add package Azure.Messaging.EventHubs
Step 2: Write the Code to Send Events

Below are examples of how to send events. Replace YOUR_EVENTHUB_CONNECTION_STRING and YOUR_EVENTHUB_NAME with your actual values.

Node.js Example


// Import the necessary classes
const { EventHubProducerClient } = require("@azure/event-hubs");

// Your Event Hubs connection string and hub name
const connectionString = "YOUR_EVENTHUB_CONNECTION_STRING";
const eventHubName = "YOUR_EVENTHUB_NAME";

async function main() {
    // Create a producer client to send events
    const producer = new EventHubProducerClient(connectionString, eventHubName);

    // Prepare an array of events to send
    const events = [
        { body: "First event" },
        { body: "Second event", properties: { key: "value" } },
        { body: { message: "A JSON event", timestamp: new Date() } }
    ];

    console.log("Sending events...");
    try {
        // Send the events in batches
        const batches = await producer.createBatch();
        for (const event of events) {
            // Try to add an event to the batch
            if (batches.tryAdd(event)) {
                continue;
            } else {
                // If the event could not be added, send the current batch and start a new one
                await producer.sendBatch(batches);
                console.log("Sent a batch of events.");
                batches.clear(); // Clear the batch to add more events
                batches.tryAdd(event); // Add the current event to the new batch
            }
        }
        // Send any remaining events in the last batch
        if (batches.count > 0) {
            await producer.sendBatch(batches);
            console.log(`Sent the final batch of ${batches.count} events.`);
        }
        console.log("All events sent successfully!");
    } catch (error) {
        console.error("Error sending events:", error);
    } finally {
        // Close the producer client
        await producer.close();
        console.log("Producer client closed.");
    }
}

main().catch(err => {
    console.error("The main function encountered an error:", err);
});
                

Python Example


# Import the necessary classes
from azure.eventhub import EventHubProducer, EventData

# Your Event Hubs connection string and hub name
CONNECTION_STR = "YOUR_EVENTHUB_CONNECTION_STRING"
EVENTHUB_NAME = "YOUR_EVENTHUB_NAME"

def send_events():
    producer = None
    try:
        # Create a producer client to send events
        producer = EventHubProducer.from_connection_string(CONNECTION_STR, EVENTHUB_NAME)

        # Prepare events to send
        events_to_send = [
            EventData("First event from Python"),
            EventData("Second event with metadata", partition_key="mykey"),
            EventData({"message": "A JSON event", "timestamp": "now"})
        ]

        print("Sending events...")
        # Send events. Events will be sent in batches automatically.
        producer.send(events_to_send)
        print("Events sent successfully!")

    except Exception as e:
        print(f"Error sending events: {e}")
    finally:
        # Close the producer client
        if producer:
            producer.close()
            print("Producer client closed.")

if __name__ == "__main__":
    send_events()
                

C# Example


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

public class EventSender
{
    // Your Event Hubs connection string and hub name
    private const string ConnectionString = "YOUR_EVENTHUB_CONNECTION_STRING";
    private const string EventHubName = "YOUR_EVENTHUB_NAME";

    public static async Task Main(string[] args)
    {
        // Create a producer client to send events
        await using (var producerClient = new EventHubProducerClient(ConnectionString, EventHubName))
        {
            // Prepare events to send
            var events = new List<EventData>
            {
                new EventData(Encoding.UTF8.GetBytes("First event from C#")),
                new EventData(Encoding.UTF8.GetBytes("Second event with metadata"), new Dictionary<string, object> { { "source", "tutorial" } }),
                new EventData(Encoding.UTF8.GetBytes("{\"message\": \"A JSON event\", \"timestamp\": \"" + DateTime.UtcNow.ToString("o") + "\"}"))
            };

            Console.WriteLine("Sending events...");
            try
            {
                // Send events in batches
                using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();

                foreach (var ev in events)
                {
                    if (!eventBatch.TryAdd(ev))
                    {
                        // If the event can't be added to the current batch, send the batch and start a new one
                        await producerClient.SendAsync(eventBatch);
                        Console.WriteLine($"Sent a batch of {eventBatch.Count} events.");
                        eventBatch.Clear(); // Clear the batch to add more events
                        eventBatch.TryAdd(ev); // Add the current event to the new batch
                    }
                }

                // Send any remaining events in the last batch
                if (eventBatch.Count > 0)
                {
                    await producerClient.SendAsync(eventBatch);
                    Console.WriteLine($"Sent the final batch of {eventBatch.Count} events.");
                }

                Console.WriteLine("All events sent successfully!");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Error sending events: {ex.Message}");
            }
        } // producerClient is automatically disposed here
        Console.WriteLine("Producer client closed.");
    }
}
                
Important:

Step 3: Run Your Code

Execute your program using your language's standard execution command (e.g., node your_script.js, python your_script.py, or dotnet run).

After running, you should see output indicating that the events have been sent successfully. You can then verify the receipt of these events using an Event Hubs consumer application or by checking the metrics in the Azure portal.

Next Steps