Kafka使用Java客户端进行访问的示例代码

网友投稿 351 2023-04-08


Kafka使用Java客户端进行访问的示例代码

本文环境如下:

操作系统:CentOS 6 32位

JDK版本:1.8.0_77 32位

Kafka版本:0.9.0.1(Scala 2.11)

1. maven依赖包

org.apache.kafka

kafka-clients

0.9.0.1

2. 生产者代码

package com.lnho.example.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;

import org.apache.kafka.clients.producer.Producer;

import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

public class KafkaProducerExample {

public static void main(String[] args) {

Properties props = new Properties();

props.put("bootstrap.servers", "master:9092");

props.put("acks", "all");

props.put("retries", 0);

props.put("batch.size", 16384);

props.put("linger.ms", 1);

props.put("buffer.memory", 33554432);

props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");

props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

Producer producer = new KafkaProducer<>(props);

for(int i = 0; i < 100; i++)

producer.send(new ProducerRecord<>("topic1", Integer.toString(i), Integer.toString(i)));

producer.close();

}

}

3. 消费者代码

package com.lnho.example.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;

import org.apache.kafka.clients.consumer.ConsumerRecords;

import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;

import java.util.Properties;

public class KafkaConsumerExample {

public static void main(String[] args) {

Properties props = new Properties();

props.put("bootstrap.servers", "master:9092");

props.put("group.id", "test");

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 consumer = new KafkaConsumer<>(props);

consumer.subscribe(Arrays.asList("topic1"));

while (true) {

ConsumerRecords records = consumer.poll(100);

for (ConsumerRecord record : records)

System.out.printf("offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value());

}

}

}

4. 执行程序

lib底下需要有:kafka-clients-0.9.0.1.jar log4j-1.2.17.jar slf4j-api-1.7.6.jar slf4j-log4j12-1.7.6.jar

生产者:

复制代码 代码如下:

java -classpath kafka-example-1.0-SNAPSHOT.jar:lib/* com.lnho.example.kafka.KafkaProducerExample

消费者:

复制代码 代码如下:

java -classpath kafka-example-1.0-SNAPSHOT.jar:lib/* com.lnho.example.kafka.KafkaConsumerExample


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:深入学习Hibernate持久化对象的三个状态
下一篇:详解Java中Comparable和Comparator接口的区别
相关文章

 发表评论

暂时没有评论,来抢沙发吧~