SpringCloud Stream笔记整理

  1. 添加kafka stream依赖

    xml 复制代码
    <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>
  2. application.yml中添加配置

    yml 复制代码
    --- #stream config
    spring:
      cloud:
        stream:
          binders:
            myKafka1:
              type: kafka
              environment:
                spring:
                  kafka:
                    bootstrap-servers: 127.0.0.1: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;
  3. 编写消费者:

    java 复制代码
    @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 ;
        }
    }
相关推荐
找不到、了1 小时前
Spring的Bean原型模式下的使用
java·spring·原型模式
超级小忍1 小时前
Spring AI ETL Pipeline使用指南
人工智能·spring
巴伦是只猫2 小时前
【机器学习笔记 Ⅲ】4 特征选择
人工智能·笔记·机器学习
不爱说话的采儿2 小时前
UE5详细保姆教程(第四章)
笔记·ue5·游戏引擎·课程设计
weixin_418813873 小时前
Python-可视化学习笔记
笔记·python·学习
Vic101013 小时前
Java 开发笔记:多线程查询逻辑的抽象与优化
java·服务器·笔记
笑鸿的学习笔记3 小时前
qt-C++笔记之setCentralWidget的使用
c++·笔记·qt
丁满与彭彭4 小时前
嵌入式学习笔记-MCU阶段-DAY01
笔记·单片机·学习
Boilermaker19924 小时前
【Java EE】SpringIoC
前端·数据库·spring
写不出来就跑路4 小时前
Spring Security架构与实战全解析
java·spring·架构