From d6abdcd079f8b73064b7f848f23442bddac66792 Mon Sep 17 00:00:00 2001 From: YunaiV <> Date: Sat, 7 Dec 2019 18:32:31 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20spring=20boot=20kafka=20?= =?UTF-8?q?=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kafkademo/producer/Demo06Producer.java | 9 +++++++++ .../producer/Demo06ProducerTest.java | 20 ++++++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lab-03/lab-03-kafka-demo-concurrency/src/main/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06Producer.java b/lab-03/lab-03-kafka-demo-concurrency/src/main/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06Producer.java index 2c9808e2..1c3916e7 100644 --- a/lab-03/lab-03-kafka-demo-concurrency/src/main/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06Producer.java +++ b/lab-03/lab-03-kafka-demo-concurrency/src/main/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06Producer.java @@ -22,4 +22,13 @@ public class Demo06Producer { return kafkaTemplate.send(Demo06Message.TOPIC, message).get(); } + public SendResult syncSendOrderly(Integer id) throws ExecutionException, InterruptedException { + // 创建 Demo01Message 消息 + Demo06Message message = new Demo06Message(); + message.setId(id); + // 同步发送消息 + // 因为我们使用 String 的方式序列化 key ,所以需要将 id 转换成 String + return kafkaTemplate.send(Demo06Message.TOPIC, String.valueOf(id), message).get(); + } + } diff --git a/lab-03/lab-03-kafka-demo-concurrency/src/test/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06ProducerTest.java b/lab-03/lab-03-kafka-demo-concurrency/src/test/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06ProducerTest.java index b89b44ff..079d9416 100644 --- a/lab-03/lab-03-kafka-demo-concurrency/src/test/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06ProducerTest.java +++ b/lab-03/lab-03-kafka-demo-concurrency/src/test/java/cn/iocoder/springboot/lab03/kafkademo/producer/Demo06ProducerTest.java @@ -24,9 +24,23 @@ public class Demo06ProducerTest { @Test public void testSyncSend() throws ExecutionException, InterruptedException { - int id = (int) (System.currentTimeMillis() / 1000); - SendResult result = producer.syncSend(id); - logger.info("[testSyncSend][发送编号:[{}] 发送结果:[{}]]", id, result); + for (int i = 0; i < 10; i++) { + int id = (int) (System.currentTimeMillis() / 1000); + SendResult result = producer.syncSend(id); +// logger.info("[testSyncSend][发送编号:[{}] 发送结果:[{}]]", id, result); + } + + // 阻塞等待,保证消费 + new CountDownLatch(1).await(); + } + + @Test + public void testSyncSendOrderly() throws ExecutionException, InterruptedException { + for (int i = 0; i < 10; i++) { + int id = 1; + SendResult result = producer.syncSendOrderly(id); + logger.info("[testSyncSend][发送编号:[{}] 发送队列:[{}]]", id, result.getRecordMetadata().partition()); + } // 阻塞等待,保证消费 new CountDownLatch(1).await();