SpringBoot使用Kafka
引入kafka依赖:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>2.6.0</version>
</dependency>
消息生产工具类:
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
public class SendMessage{
public static void sendKafkaMessage(String msg) {
Properties properties = new Properties();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, Constants.kafka_url);//kafka地址,多个地址用逗号分割
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
try {
ProducerRecord<String, String> record = new ProducerRecord<String, String>(Constants.topic, msg); //topic
kafkaProducer.send(record);
log.info("消息发送成功: {}", msg);
} finally {
kafkaProducer.close();
}
}
}
消息消费工具类:
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
public class HandlerMessage{
public static void main(String [] args){
KafkaConsumer<String, String> kafkaConsumer = new KafkaConfigUtil().initKafkaConfig();
while(true){
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(1000));
for (ConsumerRecord<String, String> record : records) {
log.info("Received Message: {}", record.value());
kafkaConsumer.commitAsync();
JSONObject kafkaMsg = JSONObject.parseObject(JSONObject.parse(record.value()).toString());
log.info("jsonObject: {}", kafkaMsg.toString());
}
}
}
}
kafka创建topic: