单线程版本适合本地调试,多线程版本适合做压测
1、引入maven依赖
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>1.1.0</version>
</dependency>
2、生产者代码
单线程版
public class MsgProducer {
public static void main(String[] args) throws InterruptedException, ExecutionException {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.60:9092,192.168.0.60:9093,192.168.0.60:9094");
/*
发出消息持久化机制参数
(1)acks=0: 表示producer不需要等待任何broker确认收到消息的回复,就可以继续发送下一条消息。性能最高,但是最容易丢消息。
(2)acks=1: 至少要等待leader已经成功将数据写入本地log,但是不需要等待所有follower是否成功写入。就可以继续发送下一条消息。这种情况下,如果follower没有成功备份数据,而此时leader
又挂掉,则消息会丢失。
(3)acks=-1或all: 这意味着leader需要等待所有备份(min.insync.replicas配置的备份个数)都成功写入日志,这种策略会保证只要有一个备份存活就不会丢失数据。
这是最强的数据保证。一般除非是金融级别,或跟钱打交道的场景才会使用这种配置。
*/
props.put(ProducerConfig.ACKS_CONFIG, "1");
//发送失败会重试,默认重试间隔100ms,重试能保证消息发送的可靠性,但是也可能造成消息重复发送,比如网络抖动,所以需要在接收者那边做好消息接收的幂等性处理
props.put(ProducerConfig.RETRIES_CONFIG, 3);
//重试间隔设置
props.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 300);
//设置发送消息的本地缓冲区,如果设置了该缓冲区,消息会先发送到本地缓冲区,可以提高消息发送性能,默认值是33554432,即32MB
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
//kafka本地线程会从缓冲区取数据,批量发送到broker,
//设置批量发送消息的大小,默认值是16384,即16kb,就是说一个batch满了16kb就发送出去
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
//默认值是0,意思就是消息必须立即被发送,但这样会影响性能
//一般设置100毫秒左右,就是说这个消息发送完后会进入本地的一个batch,如果100毫秒内,这个batch满了16kb就会随batch一起被发送出去
//如果100毫秒内,batch没满,那么也必须把消息发送出去,不能让消息的发送延迟时间太长
props.put(ProducerConfig.LINGER_MS_CONFIG, 100);
//把发送的key从字符串序列化为字节数组
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
//把发送消息value从字符串序列化为字节数组
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Producer<String, String> producer = new KafkaProducer<>(props);
int msgNum = 5;
CountDownLatch countDownLatch = new CountDownLatch(msgNum);
for (int i = 1; i <= msgNum; i++) {
Order order = new Order(i, 100 + i, 1, 1000.00);
//指定发送分区
ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("order-topic"
, 0, order.getOrderId().toString(), JSON.toJSONString(order));
//未指定发送分区,具体发送的分区计算公式:hash(key)%partitionNum
/*ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("my-replicated-topic"
, order.getOrderId().toString(), JSON.toJSONString(order));*/
//等待消息发送成功的同步阻塞方法
/*RecordMetadata metadata = producer.send(producerRecord).get();
System.out.println("同步方式发送消息结果:" + "topic-" + metadata.topic() + "|partition-"
+ metadata.partition() + "|offset-" + metadata.offset());*/
//异步方式发送消息
producer.send(producerRecord, new Callback() {
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (exception != null) {
System.err.println("发送消息失败:" + exception.getStackTrace());
}
if (metadata != null) {
System.out.println("异步方式发送消息结果:" + "topic-" + metadata.topic() + "|partition-"
+ metadata.partition() + "|offset-" + metadata.offset());
}
countDownLatch.countDown();
}
});
//送积分 TODO
}
countDownLatch.await(5, TimeUnit.SECONDS);
producer.close();
}
}
多线程版
package com.test.kafka;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MsgProducer {
//发送消息的个数
private static final int MSG_SIZE = 500000;
//负责发送消息的线程池
private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private static CountDownLatch countDownLatch = new CountDownLatch(MSG_SIZE);
/*发送消息的任务*/
private static class ProduceWorker implements Runnable {
private ProducerRecord<String, String> record;
private KafkaProducer<String, String> producer;
public ProduceWorker(ProducerRecord<String, String> record, KafkaProducer<String, String> producer) {
this.record = record;
this.producer = producer;
}
public void run() {
final String id = Thread.currentThread().getId() + "-" + System.identityHashCode(producer);
try {
producer.send(record, new Callback() {
public void onCompletion(RecordMetadata metadata, Exception exception) {
if (null != exception) {
exception.printStackTrace();
}
if (null != metadata) {
System.out.println(id + "|"
+ String.format("偏移量:%s,分区:%s",
metadata.offset(), metadata.partition()));
}
}
});
System.out.println(id + ":数据[" + record.key() + "-" + record.value() + "]已发送。");
countDownLatch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// 消费主题
String topicName = "test_datax_kafka_read";
Properties properties = new Properties();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.254.21.6:59292,10.254.21.1:59292,10.254.21.2:59292");
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
KafkaProducer<String, String> producer = new KafkaProducer(properties);
try {
//循环发送,通过线程池的方式
for (int i = 0; i < MSG_SIZE; i++) {
ProducerRecord<String, String> record = new ProducerRecord(
topicName,
null,
"{\"data\":[{\"byteSize\":5,\"rawData\":28108,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":60,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":99,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":70,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":31,\"type\":\"LONG\"},{\"byteSize\":1,\"rawData\":0,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":82,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":94,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":70,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":22,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":10,\"type\":\"LONG\"},{\"byteSize\":1,\"rawData\":1,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":89,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":14,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":38,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":20,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":50,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":30,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":13,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":36,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":53,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":42,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":11,\"type\":\"LONG\"},{\"byteSize\":1,\"rawData\":4,\"type\":\"LONG\"},{\"byteSize\":1,\"rawData\":6,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":49,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":35,\"type\":\"LONG\"},{\"byteSize\":1,\"rawData\":4,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":48,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":46,\"type\":\"LONG\"},{\"byteSize\":1,\"rawData\":1,\"type\":\"LONG\"},{\"byteSize\":2,\"rawData\":73,\"type\":\"LONG\"},{\"byteSize\":1,\"rawData\":6,\"type\":\"LONG\"},{\"byteSize\":8,\"rawData\":1659515670000,\"subType\":\"DATETIME\",\"type\":\"DATE\"}],\"size\":34}\n"
);
executorService.submit(new ProduceWorker(record, producer));
}
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
} finally {
producer.close();
executorService.shutdown();
}
}
}
3、消费者代码
单线程版
public class MsgConsumer {
public static void main(String[] args) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.60:9092,192.168.0.60:9093,192.168.0.60:9094");
// 消费分组名
props.put(ConsumerConfig.GROUP_ID_CONFIG, "testGroup");
// 是否自动提交offset
/*props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
// 自动提交offset的间隔时间
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG , "1000");*/
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
/*
心跳时间,服务端broker通过心跳确认consumer是否故障,如果发现故障,就会通过心跳下发
rebalance的指令给其他的consumer通知他们进行rebalance操作,这个时间可以稍微短一点
*/
props.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 1000);
//服务端broker多久感知不到一个consumer心跳就认为他故障了,默认是10秒
props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10 * 1000);
/*
如果两次poll操作间隔超过了这个时间,broker就会认为这个consumer处理能力太弱,
会将其踢出消费组,将分区分配给别的consumer消费
*/
props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 30 * 1000);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
// 消费主题
String topicName = "order-topic";
//consumer.subscribe(Arrays.asList(topicName));
// 消费指定分区
//consumer.assign(Arrays.asList(new TopicPartition(topicName, 0)));
//消息回溯消费
consumer.assign(Arrays.asList(new TopicPartition(topicName, 0)));
consumer.seekToBeginning(Arrays.asList(new TopicPartition(topicName, 0)));
//指定offset消费
//consumer.seek(new TopicPartition(topicName, 0), 10);
while (true) {
/*
* poll() API 是拉取消息的长轮询,主要是判断consumer是否还活着,只要我们持续调用poll(),
* 消费者就会存活在自己所在的group中,并且持续的消费指定partition的消息。
* 底层是这么做的:消费者向server持续发送心跳,如果一个时间段(session.
* timeout.ms)consumer挂掉或是不能发送心跳,这个消费者会被认为是挂掉了,
* 这个Partition也会被重新分配给其他consumer
*/
ConsumerRecords<String, String> records = consumer.poll(Integer.MAX_VALUE);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("收到消息:offset = %d, key = %s, value = %s%n", record.offset(), record.key(),
record.value());
}
if (records.count() > 0) {
// 提交offset
consumer.commitSync();
}
}
}
}
多线程版
package com.test.kafka;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MsgConsumer {
private static ExecutorService receiveMsgExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public static void main(String[] args) {
// 消费主题
String topicName = "test_datax_kafka_read";
int consumerThreadNum = 12;
for (int i = 0; i < consumerThreadNum; i++) {
receiveMsgExecutorService.submit(new KafkaConsumerThread(initConfig(), topicName));
}
}
public static Properties initConfig() {
Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "10.254.21.6:59292,10.254.21.1:59292,10.254.21.2:59292");
// 消费分组名
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "local-test-2");
// 是否自动提交offset
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
// 自动提交offset的间隔时间
properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
// 心跳时间,服务端broker通过心跳确认consumer是否故障,如果发现故障,
// 就会通过心跳下发rebalance的指令给其他的consumer通知他们进行rebalance操作,这个时间可以稍微短一点
properties.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 1000);
// 服务端broker多久感知不到一个consumer心跳就认为他故障了,默认是10秒
properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10 * 1000);
// 如果两次poll操作间隔超过了这个时间,broker就会认为这个consumer处理能力太弱,
// 会将其踢出消费组,将分区分配给别的consumer消费
properties.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 30 * 1000);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
return properties;
}
static class KafkaConsumerThread implements Runnable {
private KafkaConsumer<String, String> kafkaConsumer;
public KafkaConsumerThread(Properties properties, String topic) {
this.kafkaConsumer = new KafkaConsumer<String, String>(properties);
this.kafkaConsumer.subscribe(Arrays.asList(topic));
}
@Override
public void run() {
try {
int consumerCount = 0;
int lastConsumerCount = 0;
long lastTime = System.currentTimeMillis();
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));
for (ConsumerRecord<String, String> record : records) {
//处理消息模块
System.out.printf("收到消息:partition = %d, offset = %d, key = %s, value = %s%n", record.partition(), record.offset(), record.key(), record.value());
consumerCount++;
}
System.out.println("consumerCount:" + consumerCount);
long thisTime = System.currentTimeMillis();
long speedTime = thisTime - lastTime;
if (speedTime >= 1000L) {
lastTime = thisTime;
long speedCount = (consumerCount - lastConsumerCount)/(speedTime /1000L);
lastConsumerCount = consumerCount;
if (speedCount > 10) {
System.out.println("消费速度:" + speedCount + "条/s");
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
kafkaConsumer.close();
}
}
}
}