1、首先在 pom.xml 引入依赖
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
2、配置文件application.properties中配置生产者
###kafka
## producer
spring.kafka.producer.bootstrap-servers=192.168.56.102:9092 #根据自己的地址去配置
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
3、配置文件
application.properties中配置消费者
## consumer
spring.kafka.consumer.bootstrap-servers=192.168.56.102:9092 #根据自己的地址去配置
spring.kafka.consumer.group-id=seconds-kill #根据自己的group-id去配置
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.topic=test #根据自己的主题去配置
spring.kafka.consumer.thread=3
Linux版:
启动 Zookeeper 服务器:
cd /usr/local/kafka
bin/zookeeper-server-start.sh config/zookeeper.properties
启动 kafka 服务:
cd /usr/local/kafka
bin/kafka-server-start.sh config/server.properties &
windows版:
启动 Zookeeper 服务器:
zkServer
启动 kafka 服务:
首先cd到kafka的安装目录
.\bin\windows\kafka-server-start.bat .\config\server.properties
5、生产者发送消息
//首先引入KafkaTemplate
@Autowired
public KafkaTemplate<String, String> kafkaTempalte;
// 发送消息(topic对应上面消费者配置的主题,XXX是内容)
kafkaTempalte.send("topic","XXX");
6、消费者接收消息
@KafkaListener(id="seconds-kill", topics = "test", groupId = "seconds-kill")
public void listener(ConsumerRecord<?, ?> record) {
String[] messages = record.value().toString();
System.out.println(messages);
}