在Kafka Send()方法的Onfailure()方法调用中获取对象值

时间:2020-05-02 03:26:01

标签: java apache-kafka spring-kafka kafka-producer-api

我想获取未发送到Kafka的那些Person对象,即onFailure()方法。

1)我创建了人员类型的临时数组,并将其传递给onFailure()。但这不起作用。它总是显示相同的temp [0]不起作用。它总是打印列表中的最后一个值。 2)我试图创建本地Person对象来解决此问题。但是我遇到了编译错误

“在封闭范围内定义的局部变量pp必须是最终的或实际上是最终的”

我该如何解决此问题?

class Sender {

        @Autowired
        private KafkaTemplate<String, Person> template;

        private static final Logger LOG = LoggerFactory.getLogger(Sender.class);



        Person temp= null;

        // @Transactional("ktm")
        public void sendThem(List<Person> toSend) throws InterruptedException {
            List<ListenableFuture<SendResult<String, Person>>> futures = new ArrayList<>();


            ListenableFutureCallback<SendResult<String, Person>> callback = new ListenableFutureCallback<SendResult<String, Person>>() {

                @Override
                public void onSuccess(SendResult<String, Person> result) {
                    //LOG.info(" message success 1: " + result.getProducerRecord().value());
                    LOG.info(" message success 2: " + temp);
                }

                @Override
                public void onFailure(Throwable ex) {
                    LOG.info(" message failed : "  + temp);

                }
            };

            for (Person p : toSend) {

                temp=p;
                ListenableFuture<SendResult<String, Person>> future = template.send("t_101", temp);


                future.addCallback(callback);
            }



        }
    }

1 个答案:

答案 0 :(得分:1)

失败的发送值在 |employee_id|employee_name|employee_email|paygroup|level|dept_id| +-----------+-------------+--------------+--------+-----+-------+ |13 | null| null| null| null| null| |14 | null| null| null| null| null| |15 | null| null| null| null| null| |16 | null| null| null| null| null| |17 | null| null| null| null| null| +-----------+-------------+--------------+--------+-----+-------+ 中可用-将其强制转换为Throwable。您的KafkaProducerExceptionPerson中。

我更新了对your other question的回答。

您还可以在循环中创建一个新的回调,然后producerRecord.value()将对您可用;但是使用单个回调并从异常中获取p更为有效。