com.github.shoothzj.kafka.producer.ProducerDemo Maven / Gradle / Ivy
package com.github.shoothzj.kafka.producer;
import com.github.shoothzj.kafka.KafkaConstant;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import static java.util.stream.Collectors.joining;
public class ProducerDemo {
private static final Logger log = LoggerFactory.getLogger(ProducerDemo.class);
public KafkaProducer createProducer() {
Properties kafkaProps = new Properties();
kafkaProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
KafkaConstant.kafkaIpList.stream().map(s -> s + ":9092").collect(joining(",")));
kafkaProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KafkaConstant.defaultSerializer);
kafkaProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KafkaConstant.defaultSerializer);
KafkaProducer producer = new KafkaProducer<>(kafkaProps);
return producer;
}
public void simpleSendMessage() {
try {
createProducer().send(createProducerMessage("Topic", "value"));
} catch (Exception e) {
log.error("Log message error, exception is ", e);
}
}
public void syncSendMessage() {
try {
createProducer().send(createProducerMessage("Topic", "value")).get();
} catch (Exception e) {
log.error("Send message sync error, exception is ", e);
}
}
public void asyncSendMessage() {
createProducer().send(createProducerMessage("Topic", "value"), new DemoProducerCallback());
}
private ProducerRecord createProducerMessage(String topic, String value) {
ProducerRecord record = new ProducerRecord<>(topic, value);
return record;
}
}