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 ;
        }
    }
相关推荐
码云数智-园园9 小时前
C++20 Modules 模块详解
java·开发语言·spring
咖啡八杯10 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
Flittly10 小时前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
李少兄11 小时前
从原理到实战:Spring IoC/DI 核心知识体系与高频面试题全解
java·后端·spring
shushangyun_11 小时前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
闪闪发亮的小星星11 小时前
高斯光以及高斯光公式解释
笔记
慧一居士11 小时前
Feign的GET请求如何传递对象参数?
java·spring cloud
ofoxcoding11 小时前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
cqbzcsq12 小时前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
一杯奶茶¥13 小时前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目