0

我正在尝试向 Eventhub 发送通知,以前我使用的是https://www.nuget.org/packages/Microsoft.Azure.EventHubs/包,现在我正在使用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();
4

1 回答 1

2

为了提高效率,您将整个批次发送到同一分区,因此 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();
    }

使用分区键发布事件

于 2021-08-12T15:07:10.407 回答