如何使用Producer将自定义对象发送到Kafka主题

时间:2018-09-21 20:04:23

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

我想将我的Producer帐户类发送到我的Kafka主题,然后将与Kafka Stream进行汇总。但是,我无法发送出现错误的对象:

原因:org.apache.kafka.common.KafkaException:bank.Account不是org.apache.kafka.common.serialization.Serializer的实例

我的生产者班:

 public static void main(String[] args) {

        DataAccess dataAccess = new DataAccess();
        List<Account> accountList = dataAccess.read();

        final Logger logger = LoggerFactory.getLogger(Producer.class);
        Properties properties = new Properties();

        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"127.0.0.1:9092");
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,LongSerializer.class.getName());
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,Account.class.getName());


        KafkaProducer<Long,Account> producer = new KafkaProducer<Long, Account>(properties);



        for (Account account : accountList) {

            ProducerRecord<Long,Account> record = new ProducerRecord<Long, Account>("bank_account",account.getFromId(),account);


            producer.send(record, new Callback() {
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e == null) {
                        logger.info("Record sent successfully. \n "+ "Topic : "+recordMetadata.topic() +"\n"+
                                "Partition : " + recordMetadata.partition() + "\n"+
                                "Offset : " +recordMetadata.offset() +"\n"+
                                "Timestamp: " +recordMetadata.timestamp() +"\n");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }

                    }
                    else{
                        logger.info("Error sending producer");
                    }
                }
            });
        }


        producer.flush();
        producer.close();
    }

在此行中显示错误:

KafkaProducer<Long,Account> producer = new KafkaProducer<Long, Account>(properties);

我的帐户类别:

public class Account {

    private long fromId;
    private long amount;
    private long toId;
    private ZonedDateTime time;
}

所以我的问题是,我们如何将自定义对象发送到kafka主题?之后,我当然想使用该消息。

2 个答案:

答案 0 :(得分:2)

此行

properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,Account.class.getName());

您必须实现自己的Serializer class。它不能是普通班级。


某些人使用JSON进行序列化,其他人使用Avro或Protobuf。但是,将数据放入byte[]中只是实现细节。

答案 1 :(得分:0)

//1 
prop.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        prop.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, Employee.class.getName());

//2
 KafkaProducer<String, Employee> producer = new KafkaProducer(prop);

        Employee emp = new Employee(1, "Arun");

        ProducerRecord prodRecord = new ProducerRecord("aryan_topic", emp);
//3
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.serialization.Serializer;

import java.io.Serializable;
import java.util.Map;

//Developed by Arun Singh
public class Employee implements Serializable, Serializer {
    Integer empId;
    String empName;
    Address add;

    public Employee() {
    }

    public Employee(Integer empId, String empName, Address add) {
        this.empId = empId;
        this.empName = empName;
        this.add = add;
    }

    public Integer getEmpId() {
        return empId;
    }

    public String getEmpName() {
        return empName;
    }

    public Address getAdd() {
        return add;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public void setAdd(Address add) {
        this.add = add;
    }

    public void configure(Map configs, boolean isKey) {

    }

    public byte[] serialize(String s, Object o) {
        return new byte[0];
    }

    public byte[] serialize(String topic, Headers headers, Object data) {
        return new byte[0];
    }

    public void close() {

    }
}