Kafka 2.9.2-0.8.1.1没有producer.send的KeyedMessage参数

时间:2015-01-06 17:13:07

标签: java apache-kafka

我正在尝试用java向Kafka发送消息。我的项目是通过maven依赖使用kafka_2.9.2-0.8.1.1.jar:

<dependency>
  <groupId>org.apache.kafka</groupId>
  <artifactId>kafka_2.9.2</artifactId>
  <version>0.8.1.1</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
    </exclusion>
    <exclusion>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </exclusion>
  </exclusions>
</dependency>

我遇到的问题是我的制片人。我想发送一个KeyedMessage并通过这里的文档:http://kafka.apache.org/documentation.html#producerapi它声明producer.send方法应该为其参数采用KeyedMessage。当我检查可用于producer.send调用的选项时,它只允许将ProducerData对象作为可接受的参数。

我的代码设置如下:

    private String topic;   
    private String key;
    private Properties props = new Properties();
    private Producer<String,String> producer;

    props.put("serializer.class", "kafka.serializer.StringEncoder");
    props.put("zk.connect", "127.0.0.1:2181");  

    //create the producer
    producer = new Producer<String, String>(new ProducerConfig(props));   

    String topic = "test";
    String key = "test_key";
    String message = "test_msg";

    KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, key, message);
    producer.send(data)  <---- ERROR is here, send method not allowed param of KeyedMessage

实际错误是这样的状态:

 The method send(ProducerData<String,String>) in the type Producer<String,String> is not applicable for the arguments (KeyedMessage<String,String>)

3 个答案:

答案 0 :(得分:0)

我认为你需要定义

 props.put("partitioner.class", "example.producer.SimplePartitioner");

wiki页面说

  

第三个属性“partitioner.class”定义了用于确定要将消息发送到主题的哪个分区的类。这是可选的,但是对于任何非平凡的实现,您将要实现分区方案。稍后将详细介绍此类的实现。如果您为密钥包含一个值但尚未定义partitioner.class,则Kafka将使用默认分区程序。如果键为null,则Producer会将消息分配给随机分区。

答案 1 :(得分:0)

如果您不添加“partitioner.class”属性,则生产者将遵循该特定主题的分区之间的循环分配。

 props.put("partitioner.class", "example.producer.SimplePartitioner");

如果您不需要基于密钥的分区选择省略“partitioner.class”属性并按如下方式定义KeyedMessage,

    private String topic;   
    private String key;
    private Properties props = new Properties();
    private Producer<String,String> producer;

    props.put("metadata.broker.list", "localhost:9092");
    props.put("producers.type", "sync");
    props.put("serializer.class", "kafka.serializer.StringEncoder");
    props.put("request_final.required.acks", "1");

    //create the producer
    producer = new Producer<String, String>(new ProducerConfig(props));   

    topic = "test";
    message = "test_msg";

    KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, message);
    producer.send(data) 

答案 2 :(得分:-1)

使用

import kafka.javaapi.producer.Producer; 

您可能已经使用过

import kafka.producer.Producer;