生产者API测试
public void testProduce(){
Properties properties = new Properties();
// broker 列表
properties.put("metadata.broker.list","s100:9092");
// 串行化
properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
properties.put("request.required.acks","1");
// 创建生产者对象
Producer<String,String> producer = new KafkaProducer<String,String>(properties);
// 创建消息
ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("hadoop-kafka", "1", "hello world");
// 发送消息
producer.send(producerRecord);
// 关闭事务
producer.close();
}
消费者API测试
public void testConsume(){
Properties props = new Properties();
props.put("bootstrap.servers", "s100:9092");
props.put("zookeeper.connect","s100:2181");
props.put("zookeeper.session.timeout.ms","500");
props.put("zookeeper.sync.timeout.ms", "200");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<String,String>(props);
consumer.subscribe(Arrays.asList("foo", "bar"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records)
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
}