Azure Event Hubs - Producer SDK Guide

Connect your applications to Azure Event Hubs and send data efficiently.

Introduction to the Producer SDK

The Azure Event Hubs Producer SDK allows you to send events to an Event Hub with high throughput and reliability. Whether you're streaming telemetry data, application logs, or any other form of event data, this SDK provides the tools you need.

This guide will walk you through the essential steps of using the producer SDK, from setting up your environment to sending your first batch of events.

Getting Started

Prerequisites

  • An Azure subscription.
  • An Azure Event Hubs namespace and an Event Hub created within it.
  • Appropriate permissions to send events to the Event Hub.
  • Development environment with Node.js installed.

Installation

Install the Event Hubs producer client library for Node.js using npm:

npm install @azure/event-hubs

Sending Messages

Establishing a Connection

To send events, you first need to create a ProducerClient instance. You can connect using an Event Hubs connection string or Azure Active Directory credentials.

Using Connection String


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

const connectionString = "YOUR_EVENTHUBS_CONNECTION_STRING";
const eventHubName = "YOUR_EVENTHUB_NAME";

const producerClient = new EventHubProducerClient(connectionString, eventHubName);
                

Using Azure AD Credentials (Recommended for Production)

For production scenarios, it's recommended to use Azure AD for authentication. Ensure you have the necessary libraries installed:

npm install @azure/identity

const { EventHubProducerClient } = require("@azure/event-hubs");
const { DefaultAzureCredential } = require("@azure/identity");

const fullyQualifiedNamespace = "YOUR_EVENTHUBS_NAMESPACE.servicebus.windows.net";
const eventHubName = "YOUR_EVENTHUB_NAME";

const credential = new DefaultAzureCredential();
const producerClient = new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, credential);
                

Creating an Event Batch

Events are sent in batches. You can create a batch and add events to it:


async function sendMyEvents() {
    const batch = await producerClient.createBatch();

    batch.tryAdd({ body: "Hello Event Hubs!" });
    batch.tryAdd({ body: { timestamp: new Date(), message: "Another event" } });
    batch.tryAdd({ body: "This is a third event." });

    await producerClient.sendBatch(batch);
    console.log("Batch sent successfully!");
}
                

Sending the Batch

Once you have populated your batch, you can send it using the sendBatch method.


// Assuming producerClient is already initialized
sendMyEvents().catch((err) => {
    console.error("Error sending events:", err);
});
                

Advanced Features

Partition Key

To ensure events are sent to the same partition, you can specify a partitionKey when creating the batch or when adding individual events. This is crucial for maintaining order for related events.


const batchWithPartition = await producerClient.createBatch({ partitionKey: "user-123" });
batchWithPartition.tryAdd({ body: "Event for user 123" });
await producerClient.sendBatch(batchWithPartition);
                

Message Properties

You can add custom properties to your event messages.


batch.tryAdd({
    body: "Event with properties",
    properties: {
        customProperty: "exampleValue",
        source: "producer-app"
    }
});
                

Error Handling and Retries

The SDK includes built-in retry mechanisms for transient errors. However, for critical applications, you should implement robust error handling and logging.

API Reference

EventHubProducerClient

Constructor

new EventHubProducerClient(connectionString: string, eventHubName: string)

new EventHubProducerClient(fullyQualifiedNamespace: string, eventHubName: string, credential: TokenCredential)

createBatch(options?: CreateBatchOptions): Promise<EventHubBufferedProducerBatch>

Creates a new event batch. Options include partitionKey and partitionId.

sendBatch(batch: EventHubBufferedProducerBatch): Promise<void>

Sends a previously created event batch.

close(): Promise<void>

Closes the producer client and releases any resources.

EventData

Represents an event message.

body: any

properties?: {[key: string]: any}

partitionKey?: string