Spring Kafka KafkaTemplate 如何使用异步、同步发送消息以及区别区别

KafkaTemplate默认是异步发送

异步发送:

代码使用:

1
kafkaTemplate.send(topic,message);

其中topic,message是范指。

原理:

异步发送消息时,只要消息积累达到batch.size值或者积累消息的时间超过linger.ms(二者满足其一),producer就会把该批量的消息发送到topic中。
注:batch.size默认是16384,linger.ms默认是0

同步发送:

代码使用:

1
kafkaTemplate.send(topic,message).get();

原理:

同步发送消息时,需要在每次send()方法调用get()方法,因为每次send()方法会返回一个Future类型的值,Future的get()方法会一直阻塞,知道该线程的任务获取到返回值,即当消息发送成功。

异步发送消息回调

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ListenableFuture<SendResult<String, Message>> future = kafkaTemplate.send("testJson", message);
future.addCallback(new ListenableFutureCallback<SendResult<String, Message>>() {<!-- -->

    //发送消息成功回调
    @Override
    public void onSuccess(SendResult<String, Message> result) {<!-- -->
        System.out.println(result.getProducerRecord());
        //getRecordMetadata里面存在发送的topic和partition等信息
        System.out.println(result.getRecordMetadata());
    }
   
    //发送消息失败回调
    @Override
    public void onFailure(Throwable ex) {<!-- -->
        ex.printStackTrace();
    }

   
});