org.enodeframework.kafka.SendKafkaMessageService Maven / Gradle / Ivy
package org.enodeframework.kafka;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.enodeframework.common.exception.IORuntimeException;
import org.enodeframework.queue.ISendMessageService;
import org.enodeframework.queue.QueueMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;
import java.util.concurrent.CompletableFuture;
/**
* @author [email protected]
*/
public class SendKafkaMessageService implements ISendMessageService {
private final static Logger logger = LoggerFactory.getLogger(SendKafkaMessageService.class);
private final KafkaTemplate producer;
public SendKafkaMessageService(KafkaTemplate producer) {
this.producer = producer;
}
@Override
public CompletableFuture sendMessageAsync(QueueMessage queueMessage) {
CompletableFuture future = new CompletableFuture<>();
ProducerRecord message = KafkaTool.covertToProducerRecord(queueMessage);
producer.send(message).addCallback(new ListenableFutureCallback>() {
@Override
public void onFailure(Throwable throwable) {
logger.error("Enode message async send has exception, message: {}", message, throwable);
future.completeExceptionally(new IORuntimeException(throwable));
}
@Override
public void onSuccess(SendResult result) {
if (logger.isDebugEnabled()) {
logger.debug("Enode message async send success, sendResult: {}, message: {}", result, message);
}
future.complete(null);
}
});
return future;
}
}