Sending Events to Azure Event Hubs

A comprehensive guide for developers on how to efficiently send events to your Azure Event Hubs.

Select Language:

Introduction to Sending Events

Azure Event Hubs is a highly scalable data streaming platform and event ingestion service. Sending events to Event Hubs is a fundamental operation for many real-time data processing scenarios. This guide covers the essential steps and best practices for reliably sending events.

Core Concepts

Prerequisites

Before you can send events, ensure you have the following:

Sending Events using the Azure SDKs

The Azure SDKs provide robust libraries for interacting with Event Hubs. Here are examples for common languages:

C# Example

Using the Azure.Messaging.EventHubs NuGet package.


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

public class EventSender
{
    private const string EventHubConnectionString = "";
    private const string EventHubName = "";

    public static async Task Main(string[] args)
    {
        await SendEventAsync("Hello from C#! This is event #1.");
        await SendEventAsync("Another event from C#.");
    }

    public static async Task SendEventAsync(string eventData)
    {
        await using var producerClient = new EventDataSender(EventHubConnectionString, EventHubName);
        try
        {
            var eventBody = new EventData(Encoding.UTF8.GetBytes(eventData));
            Console.WriteLine($"Sending event: {eventData}");
            await producerClient.SendAsync(eventBody);
            Console.WriteLine("Event sent successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error sending event: {ex.Message}");
        }
    }
}
                

Best Practices for Sending Events

Advanced Scenarios

Sending Events with Custom Properties

You can attach custom metadata to your events. This is useful for adding contextual information.

// Example in C#
var eventBody = new EventData(Encoding.UTF8.GetBytes("My event data"));
eventBody.Properties.Add("CorrelationId", Guid.NewGuid().ToString());
eventBody.Properties.Add("SourceSystem", "MyApp");
await producerClient.SendAsync(eventBody);
            

Using Partition Keys

To ensure events are sent to the same partition:

// Example in C#
var eventBody = new EventData(Encoding.UTF8.GetBytes("User login event"));
await producerClient.SendAsync(eventBody, new SendEventOptions { PartitionKey = "user-123" });