使用Cloud Stream Binder的Springboot Kafka Producer错误处理

时间:2019-08-13 04:06:36

标签: java spring spring-boot spring-kafka spring-cloud-stream

我创建了一个Springboot应用程序来将消息推送到Kafka主题。该应用程序运行正常。我正在尝试的是在将消息发送到Kafka Topic时失败时处理异常。我正在使用错误通道在发送消息时跟踪错误。但是实际的问题是,我能够看到错误消息,但无法看到错误消息中失败的实际有效负载。实际上,我想记录该有效负载。

我尝试发送的JSON消息:{“ key1”:“ value1”}

服务类别:

@AllArgsConstructor
@EnableBinding(Source.class)
public class SendMessageToKafka {

    private final Source source;

    public void sendMessage(String sampleMessage) {
        source.output.send(MessageBuilder.withPayLoad(sampleMessage).build());
    }

    @ServiceActivator(inputChannel = "errorChannel")
    public void errorHandler(ErrorMessage em) {
        System.out.println(em);
    }
}

application.yml:

spring:
 cloud:
  stream:
   bindings:
    output:
     producer:
      error-channel-enabled: true

使用上述配置,当Kafka服务器关闭时,控件将进入errorHandler方法并打印消息。但是我无法从错误消息中看到实际的有效负载为{“ key1”:“ value1”}。如何从错误消息中检索到该消息?

1 个答案:

答案 0 :(得分:0)

您可以根据类型过滤负载,例如KafkaSendFailureExceptionhttps://docs.spring.io/spring-kafka/docs/2.2.0.RELEASE/reference/html/_spring_integration.html 表示 ErrorMessage 负载就是这种类型。) 之后,在我的情况下,将其转换为原始发送的消息,如下所示(通过断点分析对象以确定适当的值类型,例如 byte[]):

@ServiceActivator(inputChannel = "errorChannel")
public void errorHandler(ErrorMessage em) {
    log.debug("got error message over errorChannel: {}", em);
    if (null != em.getPayload() && em.getPayload() instanceof KafkaSendFailureException) {
        KafkaSendFailureException kafkaSendFailureException = (KafkaSendFailureException) em.getPayload();
        if (kafkaSendFailureException.getRecord() != null && kafkaSendFailureException.getRecord().value() != null
                && kafkaSendFailureException.getRecord().value() instanceof byte[]) {
            log.warn("error channel message. Payload {}", new String((byte[])(kafkaSendFailureException.getRecord().value())));
        }
    }
}