producer.Produce("test", new Message<Null, string>()如何识别发送失败
时间: 2024-05-01 10:20:05 浏览: 17
在使用 Confluent.Kafka 生产者发送消息时,可以通过回调函数来判断消息发送的结果。回调函数可以在 ProducerConfig 中进行配置。回调函数的参数包含了发送消息的结果以及消息本身。如果发送成功,那么结果中的 Error 属性将为 null;如果发送失败,那么 Error 属性将包含错误信息。
以下是一个示例代码:
```csharp
var config = new ProducerConfig
{
BootstrapServers = "localhost:9092",
// 配置回调函数
Callbacks = new DeliveryReportCallback<Null, string>((report) =>
{
if (report.Error.IsError)
{
// 发送失败
Console.WriteLine($"Delivery failed: {report.Error.Reason}");
}
else
{
// 发送成功
Console.WriteLine($"Delivered message to {report.TopicPartitionOffset}");
}
})
};
using (var producer = new ProducerBuilder<Null, string>(config).Build())
{
var message = new Message<Null, string> { Value = "Hello, Kafka!" };
producer.Produce("test", message);
}
```
在上述示例中,通过配置 `Callbacks` 属性来设置回调函数。当消息发送结果返回时,回调函数将会被调用。在回调函数中,可以根据 `Error` 属性来判断消息是否发送成功。