Springboot集成kafka精简步骤
第一步、到官网下载kafka安装包https://kafka.apache.org/downloads(新版内置了zookeeper,不用单独下载)
http://mirrors.tuna.tsinghua.edu.cn/apache/kafka/2.2.0/kafka_2.12-2.2.0.tgz
第二步、启动zookeeper 在安装目录下 cmd
启动zookeeper
.\bin\windows\zookeeper-server-start.bat config\zookeeper.properties
启动kafka-server
.\bin\windows\kafka-server-start.bat config\server.properties
第三步、在pom.xm中添加依赖
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
第四步、修改application.properties 添加
spring.kafka.consumer.group-id=test-consumer-group
注意:group-id的值与config目录下consumer.properties中的group.id的值保持一致。
第五步、添加消费者(放在可以扫描到的位置,测试可以放在Application所在目录)
package com.study.springboot;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
/**
* 消费者
*/
@Component
public class KafkaConsumer {
/**
*
* @param topics 主题 与 生产者那边相同
*/
@KafkaListener(topics = {"topic-test000"})
public void receive(String message){
System.out.println("topic-test--消费消息:" + message);
}
}
第六步、添加生产者(放在可以扫描到的位置,测试可以放在Application所在目录)
package com.study.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.UUID;
/**
* 生产者
*/
@Component
@EnableScheduling
public class KafkaProducer {
@Autowired
private KafkaTemplate<?, String> kafkaTemplate;
/**
* 定时任务
*/
@Scheduled(cron = "00/10 * * * * ?")
public void send(){
String message = UUID.randomUUID().toString();
ListenableFuture<?> future = kafkaTemplate.send("topic-test000", message);
future.addCallback(o -> System.out.println("send-topic-test-消息发送成功:" + message), throwable -> System.out.println("消息发送失败:" + message));
}
}
第七步、测试