Search code examples
azureazure-devopsazure-eventhub

How can we set partitionkey in Azure.Messaging.EventHubs


I am trying to send a notification to the Eventhub, Previously I was using https://www.nuget.org/packages/Microsoft.Azure.EventHubs/ Package and now I am doing it using https://www.nuget.org/packages/Azure.Messaging.EventHubs. Here is the code which I am using. It's working fine but I don't know how I can pass the partition key while sending the message as eventData.PartitionKey = partitionKey; property is read-only property.

                var producerClient = new EventHubProducerClient(connectionString, eventHubName);                    
                using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
                var eventData = new EventData(Encoding.UTF8.GetBytes(message));
                eventData.PartitionKey = partitionKey;
                
                if (!eventBatch.TryAdd(eventData))
                    throw new Exception($"batch size is large and cannot be sent");

                await producerClient.SendAsync(eventBatch); 
                await producerClient.DisposeAsync();

Solution

  • For efficiency you send a whole batch to the same partition, so the PartitionKey is set in the CreateBatchOptions, eg from the samples:

        var connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>";
        var eventHubName = "<< NAME OF THE EVENT HUB >>";
        
        var producer = new EventHubProducerClient(connectionString, eventHubName);
        
        try
        {
            var batchOptions = new CreateBatchOptions
            {
                PartitionKey = "Any Value Will Do..."
            };
        
            using var eventBatch = await producer.CreateBatchAsync(batchOptions);
        
            for (var index = 0; index < 5; ++index)
            {
                var eventBody = new BinaryData($"Event #{ index }");
                var eventData = new EventData(eventBody);
        
                if (!eventBatch.TryAdd(eventData))
                {
                    throw new Exception($"The event at { index } could not be added.");
                }
            }
        
            await producer.SendAsync(eventBatch);
        }
        finally
        {
            await producer.CloseAsync();
        }
    

    Publishing events with a partition key