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();