【问题标题】:No exception when unable to connect to kafka cluster无法连接kafka集群时也不例外
【发布时间】:2022-04-06 19:41:54
【问题描述】:

当程序无法连接到 kafka 集群时,我无法得到异常。 代码在控制台日志中输出异常,但我需要它抛出异常。我正在使用这个 c# 库: https://github.com/confluentinc/confluent-kafka-dotnet

ProducerConfig _configKafka = new ProducerConfig { BootstrapServers ="localhost:9092/" };

ProducerBuilder<string, string> _kafkaProducer = new ProducerBuilder<string, string>(_configKafka);
using (var kafkaProducer = _kafkaProducer.Build())
{

    try
    {
        var dr = kafkaProducer.ProduceAsync("Kafka_Messages", new Message<string, string> { Key = null, Value = $"message {i++}" });
        dr.Wait(TimeSpan.FromSeconds(10));

        if(dr.Exception!=null)
        {
            Console.WriteLine($"Delivery failed:");
        }

        var status = dr.Status;

        //Console.WriteLine($"Delivered '{dr.Value}' to '{dr.TopicPartitionOffset}'");
    }

    catch (ProduceException<Null, string> e)
    {
        Console.WriteLine($"Delivery failed: {e.Error.Reason}");
    }
}

confluent-kafka 在控制台打印的错误如下:

%3|1565248275.024|FAIL|rdkafka#producer-1| [thrd:localhst:9092/bootstrap]: localhst:9092/bootstrap: Failed to resolve 'localhst:9092': No such host is known.  (after 2269ms in state CONNECT)
%3|1565248275.024|ERROR|rdkafka#producer-1| [thrd:localhst:9092/bootstrap]: localhst:9092/bootstrap: Failed to resolve 'localhst:9092': No such host is known.  (after 2269ms in state CONNECT)
%3|1565248275.025|ERROR|rdkafka#producer-1| [thrd:localhst:9092/bootstrap]: 1/1 brokers are down

【问题讨论】:

    标签: c# error-handling .net-core apache-kafka confluent-platform


    【解决方案1】:

    要在您的应用程序中获取实际异常,您需要添加.SetErrorHandler()

        ProducerBuilder<string, string> _kafkaProducer = new ProducerBuilder<string, string>(_configKafka);
    
        using (var kafkaProducer = _kafkaProducer.SetErrorHandler((producer, error) =>
                            {
                               //You can handle error right here
    
                            }).Build())
    

    error.Reason 包含错误信息

    【讨论】:

    • 感谢奥莱格!有用。但是,将处理 3 个或更多错误。但我只想在产生消息后得到 1 个错误或异常。这可能吗?
    • 感谢 Olegl,我如何摆脱 SetErrorHandler ?,我试图抛出新的 Exception(error.Reason) 但它不会退出循环,它会永远留在 SetErrorHandler 中。 .
    【解决方案2】:

    您可以在消费者和生产者代码中同时使用 .SetLogHandler.SetErrorHandler。否则它会在没有提供太多细节的情况下默默地失败。您可以将消息转发到那里的记录器。

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 2018-04-22
      • 2022-10-24
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多