producer.send不接受keyedmessage类型

vd2z7a6w  于 2021-06-08  发布在  Kafka
关注(0)|答案(1)|浏览(387)

我尝试运行此代码,但由于producer.send()不接受keyedmessage类型,因此无法运行。
我尝试导入kafka.javaapi.producer.producer而不是kafka.producer.producer;但还是不行
代码是:

package sources;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

//import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import kafka.javaapi.producer.Producer;
//import kafka.producer.Producer;

public class ProducerCode {

    private static Producer<Integer, String> producer;
    private static final String topic= "mytopic";

    public void initialize() {
        Properties producerProps = new Properties();
        producerProps.put("metadata.broker.list", "localhost:9092");
        producerProps.put("serializer.class", "kafka.serializer.StringEncoder");
        producerProps.put("request.required.acks", "1");
        // ProducerConfig producerConfig = new ProducerConfig(producerProps);
        // have a change here**
        producer = new Producer<Integer, String>(new ProducerConfig(producerProps));
    }

    public void publishMesssage() throws Exception{            
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));               
        while (true){
            System.out.print("Enter message to send to kafka broker (Press 'Y' to close producer): ");
            String msg = null;
            msg = reader.readLine(); // Read message from console
            //Define topic name and message
            KeyedMessage<Integer, String> keyedMsg = new KeyedMessage<Integer, String>(topic, msg);

            producer.send(keyedMsg);
            // producer.send(keyedMsg); // This publishes message on given topic

            if("Y".equals(msg)){ break; }
            System.out.println("--> Message [" + msg + "] sent.Check message on Consumer's program console");
         }
         return;
    }

    public static void main(String[] args) throws Exception  {

        KafkaProducer kafkaProducer = new KafkaProducer();
        // Initialize producer
        kafkaProducer.initialize();            
        // Publish message
        kafkaProducer.publishMesssage();
        //Close the producer
        producer.close();
    }
}
eit6fx6z

eit6fx6z1#

你必须使用 ProducerRecord (代替 KeyedMessage )带构造函数 ProducerRecord(String topic, K key, V value) ```
Producer<String, String> producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<String, String>("my-topic", "key", "value"));

看到了吗https://kafka.apache.org/0100/javadoc/index.html?org/apache/kafka/clients/producer/kafkaproducer.html

相关问题