无法通过java代码向kafka主题发送消息

时间:2016-07-08 06:08:04

标签: apache-kafka

我正在使用Kafka。这是我的代码,我想向kafka服务器发送消息,主题名称为“west”,消息为“message1”。我没有收到任何错误,虽然我没有看到我在主题中发送的消息是否有任何错误这里吗?

class SimpleProducer {

  public static void main(String[] args) throws Exception{       
    Properties props = new Properties();
    props.put("bootstrap.servers","172.xxxxxxxxx:9092");
    props.put("serializer.class", "kafka.serializer.DefaultEncoder");
    props.put("acks", "1");
    props.put("retries", 1);
    props.put("batch.size", 16384);
    props.put("linger.ms", 0);
    props.put("client.id", "foo");
    props.put("buffer.memory", 33554432);
    props.put("timeout.ms", "500");
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    props.setProperty(ProducerConfig.MAX_BLOCK_MS_CONFIG, "500"); 
    props.setProperty(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, "100");

    System.out.println("ready to send msg");

    try {
        Producer<String, String> producer = new KafkaProducer<String, String>(props);

        producer.send(new ProducerRecord<String, String>("west","message1"));

        System.out.println("Message sent successfully");
        producer.close();
    }
    catch(Exception e)
    {
        System.out.println("Messgae doesn't sent successfully");
        e.printStackTrace();

    }
  }
}

2 个答案:

答案 0 :(得分:0)

您用于发送邮件的API是异步的。使用send()的形式,它有两个参数。第二个参数是一个Callback,您可以使用它来查看发送是否真的有效或某处是否有错误。

答案 1 :(得分:-1)

   producer.send(yourRecord,
                 new Callback() {
                     public void onCompletion(RecordMetadata metadata, Exception e) {
                         if(e != null) {
                            e.printStackTrace();
                         } else {
                            System.out.println("The offset of the record we just sent is: " + metadata.offset());
                         }
                     }
                 });