This section guides you through the process of sending data (events) to an Azure Event Hub. Event Hubs is a highly scalable data streaming platform and event ingestion service. Producing data efficiently is crucial for real-time analytics, batch processing, and application integration.
When producing data, consider the following:
Use your language's package manager to install the Azure Event Hubs client library.
Example (Node.js):
npm install @azure/event-hubs
Example (Python):
pip install azure-eventhubs
Initialize the Event Hubs producer client using your connection string and Event Hub name.
Example (Python):
from azure.eventhub import EventHubProducerClient
connection_str = "<YOUR_EVENT_HUBS_CONNECTION_STRING>"
eventhub_name = "<YOUR_EVENT_HUB_NAME>"
producer = EventHubProducerClient.from_connection_string(connection_str, eventhub_name)
Example (Node.js):
const { EventHubProducerClient } = require("@azure/event-hubs");
const connectionString = "<YOUR_EVENT_HUBS_CONNECTION_STRING>";
const eventHubName = "<YOUR_EVENT_HUB_NAME>";
const producer = new EventHubProducerClient(connectionString, eventHubName);
Construct your event data, potentially as a batch, and send it using the producer client.
Example (Python - Single Event):
import datetime
async def send_single_event():
async with producer:
event_data = {
"message": "Hello, Event Hubs!",
"timestamp": str(datetime.datetime.utcnow())
}
await producer.send_event(event_data)
print("Sent a single event.")
# Call the async function (requires an async context like asyncio.run())
# asyncio.run(send_single_event())
Example (Python - Batched Events):
import datetime
async def send_batched_events():
async with producer:
events = []
for i in range(5):
event_data = {
"id": i,
"message": f"Batch message {i}",
"timestamp": str(datetime.datetime.utcnow())
}
# You can also specify a partition_key here
events.append({"body": event_data, "partition_key": "my_key"})
await producer.send_batch(events)
print(f"Sent a batch of {len(events)} events.")
# Call the async function (requires an async context like asyncio.run())
# asyncio.run(send_batched_events())
Example (Node.js - Single Event):
async function sendSingleEvent() {
try {
const eventData = {
message: "Hello from Node.js!",
timestamp: new Date().toISOString()
};
await producer.send({ body: eventData });
console.log("Sent a single event.");
} catch (err) {
console.error("Error sending event:", err);
}
}
// Call the async function
// sendSingleEvent();
Example (Node.js - Batched Events):
async function sendBatchedEvents() {
try {
const events = [];
for (let i = 0; i < 5; i++) {
const eventData = {
id: i,
message: `Node.js batch message ${i}`,
timestamp: new Date().toISOString()
};
// You can also specify a partitionKey here
events.push({ body: eventData, partitionKey: "my_node_key" });
}
await producer.send(events);
console.log(`Sent a batch of ${events.length} events.`);
} catch (err) {
console.error("Error sending batch:", err);
}
}
// Call the async function
// sendBatchedEvents();
It's good practice to close the producer client when you're finished to release resources.
Example (Python):
# The `async with producer:` block handles closing automatically.
# If not using `async with`, you would call:
# await producer.close()
Example (Node.js):
// The producer is automatically managed by the client library.
// For explicit closure if needed:
// await producer.close();