Sending Messages to Azure Event Hubs

This tutorial will guide you through the process of sending messages to an Azure Event Hub using various programming languages and SDKs. Azure Event Hubs is a highly scalable data streaming platform and event ingestion service.

Prerequisites

Important Note:

Always protect your Event Hub connection string. Treat it like a password and do not expose it in client-side code or public repositories.

Sending Messages with .NET

1

Install the SDK

Install the Azure.Messaging.EventHubs NuGet package:

dotnet add package Azure.Messaging.EventHubs
2

Write the Code

Here's a C# example demonstrating how to send a single message:

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

public class EventHubSender
{
    // Replace with your Event Hub connection string and hub name
    private const string connectionString = "YOUR_EVENTHUB_CONNECTION_STRING";
    private const string hubName = "YOUR_EVENTHUB_NAME";

    public static async Task Main(string[] args)
    {
        await SendMessageAsync();
    }

    public static async Task SendMessageAsync()
    {
        // Create an EventHubProducerClient
        await using var client = new EventHubProducerClient(connectionString, hubName);

        // Create an event data
        var eventData = new EventData(Encoding.UTF8.GetBytes("Hello, Azure Event Hubs!"));

        // Send the event
        try
        {
            await client.SendAsync(new EventData[] { eventData });
            Console.WriteLine("Message sent successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error sending message: {ex.Message}");
        }
    }
}

Batching Events:

For better efficiency, you can send events in batches. Use eventHubClient.CreateBatchAsync() and batch.TryAdd(eventData).

Sending Messages with Python

1

Install the SDK

Install the azure-eventhub library:

pip install azure-eventhub
2

Write the Code

Here's a Python example:

from azure.eventhub import EventHubProducerClient
import os

# Replace with your Event Hub connection string and hub name
CONNECTION_STR = "YOUR_EVENTHUB_CONNECTION_STRING"
EVENT_HUB_NAME = "YOUR_EVENTHUB_NAME"

async def send_message():
    # Create a producer client
    producer = EventHubProducerClient.from_connection_string(
        CONNECTION_STR, EVENT_HUB_NAME
    )

    # Send a single message
    async with producer:
        try:
            await producer.send_batch([{"body": "Hello from Python!"}])
            print("Message sent successfully.")
        except Exception as e:
            print(f"Error sending message: {e}")

if __name__ == "__main__":
    import asyncio
    asyncio.run(send_message())

Sending Messages with Node.js

1

Install the SDK

Install the @azure/event-hubs package:

npm install @azure/event-hubs
2

Write the Code

Here's a Node.js example:

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

// Replace with your Event Hub connection string and hub name
const connectionString = "YOUR_EVENTHUB_CONNECTION_STRING";
const eventHubName = "YOUR_EVENTHUB_NAME";

async function sendEvent() {
  const producer = new EventHubProducerClient(connectionString, eventHubName);

  try {
    await producer.send({ body: "Hello from Node.js!" });
    console.log("Message sent successfully.");
  } catch (error) {
    console.error("Error sending message:", error);
  } finally {
    await producer.close();
  }
}

sendEvent();

Sending Messages with Java

1

Add Dependencies

Add the Event Hubs dependency to your pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-messaging-eventhubs</artifactId>
    <version>5.13.0</version><!-- Use the latest version -->
</dependency>
2

Write the Code

Here's a Java example:

import com.azure.messaging.eventhubs.EventHubProducerClient;
import com.azure.messaging.eventhubs.EventHubClientBuilder;
import com.azure.messaging.eventhubs.models.EventBatch;
import com.azure.messaging.eventhubs.models.SendEventOptions;

import java.util.Collections;

public class EventHubSender {

    // Replace with your Event Hub connection string and hub name
    private static final String CONNECTION_STRING = "YOUR_EVENTHUB_CONNECTION_STRING";
    private static final String EVENT_HUB_NAME = "YOUR_EVENTHUB_NAME";

    public static void main(String[] args) {
        sendMessage();
    }

    public static void sendMessage() {
        // Create a producer client
        EventHubProducerClient producer = new EventHubClientBuilder()
            .connectionString(CONNECTION_STRING, EVENT_HUB_NAME)
            .buildProducerClient();

        try {
            // Create an event
            byte[] data = "Hello from Java!".getBytes();
            SendEventOptions options = new SendEventOptions();

            // Send the event
            producer.send(Collections.singletonList(new com.azure.messaging.eventhubs.EventData(data)), options);
            System.out.println("Message sent successfully.");

        } catch (Exception e) {
            System.err.println("Error sending message: " + e.getMessage());
            e.printStackTrace();
        } finally {
            producer.close();
        }
    }
}

Conclusion

You have successfully learned how to send messages to Azure Event Hubs using common programming languages. For more advanced scenarios like sending batched events, partitioned sending, or handling errors, please refer to the official Azure Event Hubs SDK documentation for your specific language.