Thursday, February 8, 2024

Python Client to send messages to Azure EventHub with ConnectionString

 Run this python code to send messages both in JSON format and string, both are sent successfully. You can just run this from your end, it will sure work. Note that the messages sent in NON JSON format will not be visible but the count increases and messages sent in JSON format can be viewed from Azure UI.  Consumer can read all formats of message.

import asyncio

from azure.eventhub import EventData

from azure.eventhub.aio import EventHubProducerClient

EVENT_HUB_CONNECTION_STR =

"Endpoint=sb://genericeventhub.servicebus.windows.net/;

SharedAccessKeyName=RootManageSharedAccessKey;

SharedAccessKey=4cI6t0fjJwhf8i0ZKIjJ+uww27yCsBtnf+AEhIiC9xQ="

EVENT_HUB_NAME = "javaappeh"

async def run():   

    # Create a producer client to send messages to the event hub.

    # Specify a connection string to your event hubs namespace and

    # the event hub name.

    producer = EventHubProducerClient.from_connection_string(

        conn_str=EVENT_HUB_CONNECTION_STR, eventhub_name=EVENT_HUB_NAME

    )

    async with producer:

        # Create a batch.

        event_data_batch = await producer.create_batch()

        # Add events to the batch.

        messagebody = '{"KEY20":"VALUE20","KEY21":"VALUE21","timestamp":"2024-05-17T01:17:00Z"}'

        event_data_batch.add(EventData(messagebody))

        #event_data_batch.add(EventData("Second event"))       

        await producer.send_batch(event_data_batch)

asyncio.run(run())



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...