package com.muyu.event.config;

import jakarta.annotation.Nullable;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.ProducerListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class KafkaSendResultHandler implements ProducerListener<Object,Object> {

    @Autowired
    private KafkaTemplate<Object,Object> kafkaTemplate;

    /**
     * bean 初始化方法
     */
    @PostConstruct
    public void init(){
        this.kafkaTemplate.setProducerListener(this);
    }

    /**
     * 消息发送到Kafka成功的回调
     * @param producerRecord
     * @param recordMetadata
     */
    @Override
    public void onSuccess(ProducerRecord producerRecord, RecordMetadata recordMetadata){
        System.out.println("信息发送成功："+ producerRecord.toString());
    }

    /**
     * 息发送到 Kafka 失败的回调
     * @param producerRecord the failed record
     * @param recordMetadata The metadata for the record that was sent (i.e. the partition
     * and offset). If an error occurred, metadata will contain only valid topic and maybe
     * the partition. If the partition is not provided in the ProducerRecord and an error
     * occurs before partition is assigned, then the partition will be set to
     * RecordMetadata.UNKNOWN_PARTITION.
     * @param exception the exception thrown
     */
    @Override
    public void onError(ProducerRecord producerRecord, @Nullable RecordMetadata recordMetadata,
                        Exception exception){
        System.out.println("消息发送失败: "+ producerRecord.toString());
    }













}
