基础功能及配置
-
环境:spring-boot:2.6.11, spring-cloud:2021.0.4
-
添加kafka stream依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-stream-binder-kafka</artifactId> </dependency> </dependencies>
-
application.yml中添加配置
--- #stream config spring: cloud: stream: binders: myKafka1: type: kafka environment: spring: cloud: stream: kafka: binder: brokers: 192.168.99.51:9092 bindings: helloFunc-in-0: destination: hello-topic group: hello-local-test-10 binder: myKafka1 consumer: batch-mode: true helloFunc-out-0: destination: hello-topic group: hello-local-test-10 binder: myKafka1 consumer: batch-mode: true # 注意 function 节点与stream 同级,而非子节点 function: definition: helloFunc;
-
编写消费者:
@Slf4j @Component @RequiredArgsConstructor public class HelloConsumer { @Bean public Consumer<Message<List<String>>> helloFunc() { return message -> { log.info("---------------------> "); List<String> list = message.getPayload(); boolean result = this.handle(list); if (result) { Acknowledgment acknowledgment = message.getHeaders().get(KafkaHeaders.ACKNOWLEDGMENT, Acknowledgment.class); if (acknowledgment != null) { acknowledgment.acknowledge(); } } else { throw new RuntimeException("消费数据出错!"); } }; } private boolean handle(List<String> list){ log.info("list size : {}", list.size()); if (!CollectionUtils.isEmpty(list)){ log.info("group first message : {}", list.get(0)); } return true ; } }
SSL 配置
-
application.yml中补充ssl配置
--- # ssl config spring: cloud: stream: kafka: binder: configuration: security.protocol: SSL ssl.endpoint.identification.algorithm: "" ssl.truststore.location: "classpath:client.truststore.jks" ssl.truststore.password: "hello123"