1、引入依赖
<dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> <version>2.8.6</version> </dependency>
2、配置
server: port: 9099 spring: kafka: producer: bootstrap-servers: XX.XX.XX.XX:9092 key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer #sasl配置,按需配置 properties: sasl.mechanism: PLAIN security.protocol: SASL_PLAINTEXT sasl.jaas.config: org.apache.kafka.common.security.scram.ScramLoginModule required username=XXXpassword=XXX; consumer: bootstrap-servers: XX.XX.XX.XX:9092 key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer #sasl配置,按需配置 properties: sasl.mechanism: PLAIN security.protocol: SASL_PLAINTEXT sasl.jaas.config: org.apache.kafka.common.security.scram.ScramLoginModule required username=XXX password=XXX;
3、测试
@Autowired KafkaTemplate<String,String> kafkaTemplate; @Test void contextLoads() { for (int i = 0; i < 100; i++) { kafkaTemplate.send("hello","hello"+i); } }
如日志打印:Connection to node 0 (/127.0.0.1:9092)
#进入kafka安装目录 /usr/local/kafka_2.12-3.5.1/config #编辑配置文件 vim server.properties # 允许外部端口连接 listeners=PLAINTEXT://0.0.0.0:9092 # 外部代理地址 advertised.listeners=PLAINTEXT://192.168.157.101:9092
重启kafka服务