1、安装依赖
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
2、配置文件
spring.kafka.bootstrap-servers:localhost:9092
spring.kafka.producer.key-serializer:org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
spring.kafka.consumer.group-id=testGroup
spring.kafka.consumer.key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
3、生产者代码
@Service
public class ProviderService {
public static final String TOPIC = "xxxxxxx";
@Resource
private KafkaTemplate<String, String> kafkaTemplate;
public void send(String key,String message) {
// 发送消息
kafkaTemplate.send(TOPIC, key,message);
System.out.println("Provider= " + message);
}
}
4、消费者测试代码
package com.example.hat.service.Impl;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class ConsumerService {
@KafkaListener(topics = {"xxxxxxxx"})
public void onMessage1(ConsumerRecord<?, ?> record){
// 消费的哪个topic、partition的消息,打印出消息内容
System.out.println("简单消费:"+record.topic()+"-"+record.partition()+"-"+record.key()+"-"+record.value());
}
}