WSL中Docker安装Kafka
Apach Kafka是一款分布式流处理平台,用于实时构建流处理应用,之前常用于构建消息系统
在WSL上的Docker中安装Kafka
1.拉取镜像
# 拉取zookeeper镜像
docker pull wurstmeister/zookeeper:3.4.13
# 拉取kafka镜像
docker pull wurstmeister/kafka:2.13-2.7.0
2.安装Zookeeper
docker run -d --name zookeeper -p 2181:2181 -v /etc/localtime:/etc/localtime wustmeister/zookeeper:3.4.13
3.安装Kafka
docker run -d --name kafka -p 9092:9092 -v /etc/localtime:/etc/localtime -e KAFKA_BROKER_ID=1 -e KAFKA_ZOOKEEPER_CONNECT=172.27.162.117:2181 -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://172.27.164.117 -e KAFKA_LISTENERS=PLAINTEXT://172.27.164.117 wurstmeister/kafka:2.13-2.7.0
KAFKA_BROKER_ID 表示集群中区分
KAFKA_ZOOKEEPER_CONNECT 指定zookeeper的连接地址
KAFKA_ADVERTISED_LISTENERS 指定
KAFKA_LISTENERS 指定监听地址
SpringBoot集成Kafka
1.pom依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.application配置
spring:
kafka:
producer:
bootstrap-servers: 172.27.164.117:9092
3.启动类及测试代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@SpringBootApplication
@RestController
@Slf4j
public class KafkaApp {
public static void main(String[] args) {
SpringApplication.run(KafkaApp.class,args);
}
@Resource
private KafkaTemplate<Object,Object> kafkaTemplate;
@GetMapping("/send")
public void send(String message){
kafkaTemplate.send("test_topic",message);
}
@KafkaListener(id = "test_group",topics = {"test_topic"})
public void get(String message){
log.info(message);
}
}
4.启动服务,接口访问send接口,查看命令行是否