使用前准备
下载kafka,地址http://mirror.bit.edu.cn/apache/kafka/2.2.0/kafka_2.12-2.2.0.tgz
解压
启动ZooKeeper
bin/zookeeper-server-start.sh config/zookeeper.properties
启动kafka
bin/kafka-server-start.sh config/server.properties
windows启动方式
.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties
.\bin\windows\kafka-server-start.bat .\config\server.properties
项目配置
1,maven
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
2,yml配置
spring:
kafka:
bootstrap-servers: 127.0.0.1:9092
producer:
acks: all
retries: 0
batch-size: 16384
buffer-memory: 33554432
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
consumer:
group-id: group-001
enable-auto-commit: true
auto-commit-interval: 60s
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
3,消息生产者
@Component
public class MyKafkaProducer {
private final KafkaTemplate<String, String> kafkaTemplate;
@Autowired
public MyKafkaProducer(KafkaTemplate<String, String> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
public void sendMsg(Object t, String topic) {
String s = JSON.toJSONString(t);
sendMsg(s, topic);
}
public void sendMsg(String t, String topic) {
kafkaTemplate.send(new ProducerRecord<>(topic, t));
}
}
4,消息消费者
@KafkaListener(topics = {"your topic"})
public void receiveMsg(String msg) {
System.out.println(msg);
}