springboot整合kafka 30
阿新 • • 發佈:2021-02-10
技術標籤:springspring bootkafkajavaweblogic
1、環境約束
- win10 64位作業系統
- idea2018.1.5
- maven-3.0.5
- jdk-8u162-windows-x64
2、前提約束
- 完成springboot建立web專案 https://www.jianshu.com/p/de979f53ad80
注意,作者使用的springboot版本是2.1.8.RELEASE - 完成安裝kafka,並啟動,且建立佇列testhttps://www.jianshu.com/p/1a7b9970d073
2、操作步驟
- 加入依賴
<dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency>
- 修改配置檔案
server.port=8080
spring.kafka.bootstrap-servers=localhost:9092
# 指定預設消費者group id
spring.kafka.consumer.group-id=group-id
- 建立生產者
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class Producer { @Autowired private KafkaTemplate kafkaTemplate; @GetMapping("/send/{msg}") public void sendlog(@PathVariable("msg")String msg){ kafkaTemplate.send("test",msg); } }
- 建立消費者
import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component; @Component public class Consumer { @KafkaListener(topics = {"test"}) public void consumer(ConsumerRecord consumerRecord){ Object value = consumerRecord.value(); System.out.println(value); } }
- 啟動boot專案,在瀏覽器中訪問http://localhost:8080/send/ali,在命令列中就能看到以下輸出:
消費者列印字串
以上就是springboot中整合kafka的過程。