@Value("${kafka.topic}")
private String topic;
public boolean sendMsgSync(String key, String msg) {
logger.info(">>>>>------producer msg: [{}]", msg);
final boolean[] ok = {true};
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, msg);
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(record);
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onFailure(@NonNull Throwable throwable) {
logger.error("sent message=[{}] failed!", msg, throwable);
ok[0] = false;
}
@Override
public void onSuccess(SendResult<String, String> result) {
logger.info("sent message=[{}] with offset=[{}] success!", msg, result.getRecordMetadata().offset());
}
});
try {
// 因为是异步发送,所以我们等待,最多10s
future.get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
logger.error("waiting for kafka send finish failed!", e);
return false;
}
return ok[0];
}