使用Spring Cloud Stream集成消息中间件

简介: Spring Cloud Stream 是一个用于构建消息驱动微服务的框架。它封装了与消息中间件的交互,提供了一致的编程模型;避免了开发人员需要关注底层消息中间件相关细节的问题。

一、概述

1 什么是Spring Cloud Stream

Spring Cloud Stream 是一个用于构建消息驱动微服务的框架。它封装了与消息中间件的交互,提供了一致的编程模型;避免了开发人员需要关注底层消息中间件相关细节的问题。

2 Spring Cloud Stream与消息中间件的关系

Spring Cloud Stream 可以和多种不同的消息中间件集成,包括 RabbitMQ, Kafka, AWS Kinesis等。通过向应用程序中添加 Spring Cloud Stream 相关的依赖,我们就可以在代码层面上轻松切换不同消息中间件,而无需修改其它代码。

二、Spring Cloud Stream的核心概念

1 Binder

Binder 是 Spring Cloud Stream 的核心组件之一,是连接消息中间件和应用程序的桥梁。通过配置 Binder,我们可以指定应用程序使用哪种消息中间件。Binder 另外的功能还包括序列化和反序列化消息、流控(backpressure)、错误处理等。

在应用程序中我们可以使用 @EnableBinding 注解来指定绑定器。

@SpringBootApplication
@EnableBinding(SampleBinding.class)
public class SampleApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(SampleApplication.class, args);
    }
}

interface SampleBinding {
   
    @Input
    MessageChannel input();

    @Output
    MessageChannel output();
}

2 Destination

Destination 可以被理解为发送或接收消息的目标地点。在 Spring Cloud Stream 中,Destination 由 DestinationResolver 进行解析。它通常包括 destination name(名称), group name(组名称)等信息。

3 Channel

Channel 是指在应用程序中用来发送或接收消息的端点。Spring Cloud Stream 中的 Channel 类型主要有三种,分别是 Source, Sink 和 Processor。

Source Channel(一般用于消息的生产者)

在应用程序中使用 @Output 注解定义一个 Source Channel,发送消息到这个 Channel 的时候会自动将消息发送到相应的消息中间件目标地址上。

例如:

@EnableBinding(Source.class)
public class SampleSource {
   

    @Autowired
    private Source source;

    @Scheduled(fixedDelay = 1000L)
    public void sendMessage() {
   
        this.source.output().send(MessageBuilder.withPayload(new Message("hello")).build());
    }

}

Sink Channel(一般用于消息的消费者)

在应用程序中使用 @Input 注解定义一个 Sink Channel,当有新消息到达应用程序时,就会自动将消息从 MessageChannel 接收,并使其可供应用程序处理。

例如:

@EnableBinding(Sink.class)
public class SampleSink {
   

    @ServiceActivator(inputChannel = Sink.INPUT)
    public void receiveMessage(Message<String> message) {
   
        // handle message payload here
    }

}

Processor Channel(同时既是消息的生产者也是消费者)

Processor Channel 可以看作是 Source Channel 和 Sink Channel 的超集,既可以将数据写入(生产),又可以将数据读取(消费)。

例如:

@EnableBinding(Processor.class)
public class SampleProcessor {
   

    @Transformer(inputChannel = "input", outputChannel = "output")
    public String transform(String payload) {
   
        return payload.toUpperCase();
    }

}

4 Source和Sink

Spring Cloud Stream 提供了封装好的 Source 和 Sink 类型用于简化开发。在应用程序中使用时,借助 @EnableBinding 注解将 Source 或者 Sink 绑定到对应的 Binder 上。例如,Sink 用于消费消息,示例代码如下:

@EnableBinding(Sink.class)
public class SampleSink {
   

    @StreamListener(Sink.INPUT)
    public void receive(Message<String> message) {
   
        // handle message here
    }

}

而 Source 则用于生产消息,示例代码如下:

@EnableBinding(Source.class)
public interface SampleSource {
   

    @Output
    MessageChannel output();

}

@Service
public class MyService {
   

    private final SampleSource source;

    public MyService(SampleSource source) {
   
        this.source = source;
    }

    public void someMethod() {
   
        this.source.output().send(MessageBuilder.withPayload("hello world").build());
    }
}

三、Spring Cloud Stream的基本使用流程

1 准备工作

在一个Spring Boot应用中引入spring-cloud-starter-stream-{binder}依赖(这里的{binder}代表使用的消息中间件,如Kafka、RabbitMQ等)如果需要发送和接收消息,则还需引入spring-cloud-stream。

2 定义消息通道

通过定义@Input和@Output注解来定义输入输出通道,例如:

public interface MyProcessor {
   
    String INPUT = "my-input";
    String OUTPUT = "my-output";

    @Input(INPUT)
    SubscribableChannel input();

    @Output(OUTPUT)
    MessageChannel output();
}

以上代码定义了一个MyProcessor接口,有一个名为"my-input"的输入通道和一个名为"my-output"的输出通道。

3 使用Source和Sink发送和接收消息

通过使用Spring Cloud Stream提供的Source和Sink接口,我们可以方便地发送和接收消息。例如:

@Autowired
private Source source;

@Autowired
private Sink sink;

...

source.output().send(MessageBuilder.withPayload("hello").build());

String message = (String) sink.input().receive().getPayload();

以上代码示例中通过@Autowired注解自动装配了一个Source和Sink实例,并在output()方法和input()方法中分别指定了发送和接收消息的通道。

4 配置Binder与消息中间件的集成

在application.properties或application.yml配置文件中,可以通过spring.cloud.stream.{binder}.xxx配置项配置Binder的相关属性。同时也需要指定消息中间件的相关信息,如下示例:

# Kafka配置示例
spring.cloud.stream.kafka.binder.brokers=localhost:9092
spring.cloud.stream.kafka.binder.auto-create-topics=true
spring.cloud.stream.kafka.binder.configuration.foo=bar

# RabbitMQ配置示例
spring.cloud.stream.rabbit.bindings.my-output.destination=my-exchange
spring.cloud.stream.rabbit.bindings.my-output.producer.routing-key-expression=headers['myKey']
spring.cloud.stream.rabbit.bindings.my-input.destination=my-queue
spring.cloud.stream.rabbit.bindings.my-input.consumer.bindingRoutingKey=my-routing-key

四、消息处理与异步处理流程的优化

1 消息切分与批处理

使用Spring Cloud Stream可以通过配置相关参数,实现消息的切分和批量处理。具体可以参考Binder的相关文档。

2 基于函数式编程模型的消息处理方式

在基于函数式编程模型的处理方式中可以通过定义一个Function接口,并在其中编写消息处理逻辑,例如:

@Bean
public Function<String, String> uppercase() {
   
    return String::toUpperCase;
}

以上代码示例中,我们定义了一个名为uppercase的Bean,其类型为Function,即将输入的字符串转换为大写后输出。

3 基于反应式编程模型的消息处理方式

在基于反应式编程模型的处理方式中可以使用reactive-streams或reactor提供的相关类和接口,对消息进行异步处理。具体可以参考Spring Cloud Stream的相关文档。

五、Spring Cloud Stream常见问题及解决方案

1 Binder的选择与配置

Binder是Spring Cloud Stream的核心组件它实现了与MQ中间件的交互。Spring Cloud Stream支持多种Binder,如RabbitMQ、Kafka等。我们需要根据实际情况选择适合的Binder,并进行相应的配置。

1.1 Binder的选择

选择Binder时需要考虑以下因素:

  • 应用对MQ中间件的依赖度
  • MQ中间件的性能和可靠性
  • 开发和维护成本

1.2 Binder的配置

Binder的配置包括通用配置和具体Binder的配置,通用配置如下:

spring.cloud.stream:
  bindings:
    input: #input定义
      destination: inputTopic #指定发送到哪个Topic
      content-type: application/json #消息类型
    output: #output定义
      destination: outputTopic #指定发送到哪个Topic
      content-type: application/json #消息类型
  binders:
    binder1: #binder定义
      type: rabbit
      environment:
        spring:
          rabbitmq:
            host: rabbit-server-host #RabbitMQ服务器主机名或IP地址
            port: 5672 #RabbitMQ服务器端口
            username: guest #用户名
            password: guest #密码

2 消息丢失和重复消费的问题

在实际业务中可能会遇到消息丢失和重复消费的问题。为了解决这些问题可以采用以下方法:

  • 持久化消息:对于重要的消息,可以将其持久化到磁盘上,一旦发生宕机等故障情况,消息不会丢失。
  • 消息去重:可以通过在消费端记录消费者已经消费的消息ID,避免重复消费。
  • 手动ACK:将消费模式从自动ACK改为手动ACK,确保消息在被正确处理后才进行ACK确认,避免重复消费。

3 如何监控和调优消息处理性能

为了保证应用的高性能和可靠性需要监控和调优消息处理性能。可以采用以下方法:

  • 监控指标:可以通过Spring Cloud Stream提供的监控指标,监控消息的发送和消费量、延迟等信息。
  • 调优参数:可以根据业务需求,调整消息的批处理大小、线程池大小等参数,提高处理性能。

六、案例分析

1 使用Spring Cloud Stream集成RabbitMQ实现消息队列

//引入相关依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

//定义消息发送接口
public interface MessageSender {
   
    @Output("myMessageChannel")   //使用@Output注解声明消息通道名称
    MessageChannel output();
}

//定义消息接收接口
public interface MessageReceiver {
   
    @Input("myMessageChannel")    //使用@Input注解声明消息通道名称
    SubscribableChannel input();
}

//使用@EnableBinding注解启用绑定功能,连接RabbitMQ
@SpringBootApplication
@EnableBinding({
   MessageSender.class, MessageReceiver.class})
public class RabbitMQApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(RabbitMQApplication.class, args);
    }

    //在controller中注入消息发送接口,并调用output()方法发送消息
    @Autowired
    private MessageSender messageSender;

    @GetMapping("/send")
    public void sendMessage() {
   
        String message = "Hello RabbitMQ!";
        messageSender.output().send(MessageBuilder.withPayload(message).build());
    }

    //在Service中注入消息接收接口,并使用@StreamListener注解监听消息
    @Autowired
    private MessageReceiver messageReceiver;

    @StreamListener("myMessageChannel")
    public void receiveMessage(String message) {
   
        System.out.println("Received message: " + message);
    }
}

2 使用Spring Cloud Stream集成Kafka实现消息流处理

//引入相关依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>

//定义消息发送接口
public interface MessageSender {
   
    @Output("myMessageChannel")   //使用@Output注解声明消息通道名称
    MessageChannel output();
}

//定义消息接收接口
public interface MessageReceiver {
   
    @Input("myMessageChannel")    //使用@Input注解声明消息通道名称
    SubscribableChannel input();
}

//使用@EnableBinding注解启用绑定功能,连接Kafka
@SpringBootApplication
@EnableBinding({
   MessageSender.class, MessageReceiver.class})
public class KafkaApplication {
   
    public static void main(String[] args) {
   
        SpringApplication.run(KafkaApplication.class, args);
    }

    //在controller中注入消息发送接口,并调用output()方法发送消息
    @Autowired
    private MessageSender messageSender;

    @GetMapping("/send")
    public void sendMessage() {
   
        String message = "Hello Kafka!";
        messageSender.output().send(MessageBuilder.withPayload(message).build());
    }

    //在Service中注入消息接收接口,并使用@StreamListener注解监听消息
    @Autowired
    private MessageReceiver messageReceiver;

    @StreamListener("myMessageChannel")
    public void receiveMessage(String message) {
   
        System.out.println("Received message: " + message);
    }
}

七、小结回顾

Spring Cloud Stream的优缺点

优点:

  • 简化了消息中间件的使用复杂度,提高了开发效率。
  • 支持多种消息中间件,灵活性强。
  • 提供了一致性的编程模型,使得应用程序更易于扩展和升级。

缺点:

  • 对于某些高级配置和功能,仍然需要对消息中间件有一定的了解。
  • 运行时性能可能会受到一定影响。
目录
相关文章
|
7月前
|
消息中间件 存储 Java
RabbitMQ 和 Spring Cloud Stream 实现异步通信
本文介绍了在微服务架构中,如何利用 RabbitMQ 作为消息代理,并结合 Spring Cloud Stream 实现高效的异步通信。内容涵盖异步通信的优势、RabbitMQ 的核心概念与特性、Spring Cloud Stream 的功能及其与 RabbitMQ 的集成方式。通过这种组合,开发者可以构建出具备高可用性、可扩展性和弹性的分布式系统,满足现代应用对快速响应和可靠消息传递的需求。
379 2
RabbitMQ 和 Spring Cloud Stream 实现异步通信
|
6月前
|
PyTorch 算法框架/工具 异构计算
75_TPU集成:Google Cloud加速
在大型语言模型(LLM)训练和推理的竞赛中,计算硬件的选择直接决定了研发效率和成本。Google的Tensor Processing Unit(TPU)作为专为AI计算设计的专用芯片,正逐渐成为大规模LLM开发的首选平台之一。随着2025年第七代TPU架构Ironwood的发布,Google在AI计算领域再次确立了技术领先地位。
1475 0
|
缓存 供应链 物联网
如何将 Salesforce IoT Cloud 与其他系统集成
Salesforce IoT Cloud 可通过其开放的 API 和集成云平台轻松与外部系统集成,实现数据交换和流程自动化,支持多种协议和标准,帮助企业构建智能物联网应用。
|
Java Maven Docker
gitlab-ci 集成 k3s 部署spring boot 应用
gitlab-ci 集成 k3s 部署spring boot 应用
|
SQL Java 中间件
【YashanDB知识库】yasdb jdbc驱动集成BeetISQL中间件,业务(java)报autoAssignKey failure异常
在BeetISQL 2.13.8版本中,客户使用batch insert向yashandb表插入数据并尝试获取自动生成的sequence id时,出现类型转换异常。原因是beetlsql在prepareStatement时未指定返回列,导致yashan JDBC驱动返回rowid(字符串),与Java Bean中的数字类型tid不匹配。此问题影响业务流程,使无法正确获取sequence id。解决方法包括:1) 在batchInsert时不返回自动生成的sequence id;2) 升级至BeetISQL 3,其已修正该问题。
【YashanDB知识库】yasdb jdbc驱动集成BeetISQL中间件,业务(java)报autoAssignKey failure异常
|
Cloud Native Java Nacos
springcloud/springboot集成NACOS 做注册和配置中心以及nacos源码分析
通过本文,我们详细介绍了如何在 Spring Cloud 和 Spring Boot 中集成 Nacos 进行服务注册和配置管理,并对 Nacos 的源码进行了初步分析。Nacos 作为一个强大的服务注册和配置管理平台,为微服务架构提供
4806 14
|
存储 JavaScript 开发工具
基于HarmonyOS 5.0(NEXT)与SpringCloud架构的跨平台应用开发与服务集成研究【实战】
本次的.HarmonyOS Next ,ArkTS语言,HarmonyOS的元服务和DevEco Studio 开发工具,为开发者提供了构建现代化、轻量化、高性能应用的便捷方式。这些技术和工具将帮助开发者更好地适应未来的智能设备和服务提供方式。
基于HarmonyOS 5.0(NEXT)与SpringCloud架构的跨平台应用开发与服务集成研究【实战】
|
消息中间件 Java Kafka
【Azure Kafka】使用Spring Cloud Stream Binder Kafka 发送并接收 Event Hub 消息及解决并发报错
reactor.core.publisher.Sinks$EmissionException: Spec. Rule 1.3 - onSubscribe, onNext, onError and onComplete signaled to a Subscriber MUST be signaled serially.
262 6
|
NoSQL Java API
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
2660 0
|
存储 安全 Java
Spring Boot 3 集成Spring AOP实现系统日志记录
本文介绍了如何在Spring Boot 3中集成Spring AOP实现系统日志记录功能。通过定义`SysLog`注解和配置相应的AOP切面,可以在方法执行前后自动记录日志信息,包括操作的开始时间、结束时间、请求参数、返回结果、异常信息等,并将这些信息保存到数据库中。此外,还使用了`ThreadLocal`变量来存储每个线程独立的日志数据,确保线程安全。文中还展示了项目实战中的部分代码片段,以及基于Spring Boot 3 + Vue 3构建的快速开发框架的简介与内置功能列表。此框架结合了当前主流技术栈,提供了用户管理、权限控制、接口文档自动生成等多项实用特性。
1108 8

热门文章

最新文章