我们如何在 Azure.Messaging.EventHubs 中设置 partitionkey

How can we set partitionkey in Azure.Messaging.EventHubs

我正在尝试向 Eventhub 发送通知,之前我使用的是 https://www.nuget.org/packages/Microsoft.Azure.EventHubs/ Package and now I am doing it using https://www.nuget.org/packages/Azure.Messaging.EventHubs。这是我正在使用的代码。它工作正常,但我不知道如何在发送消息时传递分区键,因为 eventData.PartitionKey = partitionKey; 属性 是只读的 属性.

                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();

为了提高效率,您将整个批次发送到同一个分区,因此 PartitionKey 设置在 CreateBatchOptions 中,例如来自样本:

    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