kafka之使用java连接
1、导入kafka所需要的包(最后附maven依赖)
安装kafka时,解压后就有kafka需要的jar包,如下图所示:
现在只需要导入这四个:kafka-clients-2.1.1.jar、log4j-1.2.17.jar、slf4j-api-1.7.25.jar、slf4j-log4j12-1.7.25.jar
2、生产者类示例
public class ProducerDemo { private void execMsgSend() throws Exception{ Properties props = new Properties(); props.put("bootstrap.servers", "192.168.23.111:9092"); props.put("acks", "1"); props.put("retries", 0); props.put("batch.size", 16384); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> procuder = new KafkaProducer<String, String>(props); String topic = "mydemo1"; for (int i = 1; i <= 10; i++) { String value = " this is another message_" + i; ProducerRecord<String,String> record = new ProducerRecord<String, String>(topic,i+"",value); procuder.send(record,new Callback() { @Override public void onCompletion(RecordMetadata metadata, Exception exception) { System.out.println("message send to partition " + metadata.partition() + ", offset: " + metadata.offset()); } }); System.out.println(i+" ---- success"); Thread.sleep(1000); } System.out.println("send message over."); procuder.close(); }
public static void main(String[] args) throws Exception{ ProducerDemo test1 = new ProducerDemo(); test1.execMsgSend(); } }
3、消费者类示例
public class ConsumerDemo {
public static void main(String[] s){ Properties props = new Properties(); props.put("bootstrap.servers", "192.168.23.111:9092"); props.put("group.id", "1"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("session.timeout.ms", "30000"); 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<>(props); consumer.subscribe(Arrays.asList("mydemo1")); while (true) { System.out.println("poll start..."); ConsumerRecords<String, String> records = consumer.poll(100); int count = records.count(); System.out.println("the numbers of topic:" + count); for (ConsumerRecord<String, String> record : records){ System.out.printf("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value()); System.out.println(); } } } }
4、所需依赖
<dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>2.1.1</version> </dependency>