1、什么是SpringCloud Stream
Spring Cloud Stream是一个用于构建消息驱动的微服务应用程序的框架,它使用 Spring Integration 可以与多个消息代理建立连接,例如kafka、rabbitMQ等消息中间件。应用程序通过 Spring Cloud Stream 注入 input 和 output 通道,然后通道通过指定绑定抽象 Binder 实现与消息代理连接。所以,当需要切换消息中间件时,几乎不需要修改代码,只需要更改配置就可以完成。
2、基本概念
整体架构图如下所示:
Inputs代表消息输入通道,框架自带的输入通道接口是Sink
public interface Sink {
/**
* 输入通道的名称
*/
String INPUT = "input";
/**
* 返回输入通道
* @return input channel.
*/
@Input(Sink.INPUT)
SubscribableChannel input();
}
outputs代表消息输出通道,框架自带的输出通道接口是Source
public interface Source {
/**
* 输出通道的名称
*/
String OUTPUT = "output";
/**
* 返回输出通道
* @return output channel
*/
@Output(Source.OUTPUT)
MessageChannel output();
}
同时支持输入、输出通道的是Processor
public interface Processor extends Source, Sink {
}
Binder 可以理解为应用程序与消息中间件的抽象接口,支持如下几个中间件:
- RabbitMQ
- Apache Kafka
- Kafka Streams
- Amazon Kinesis
- Google PubSub
- Azure Event Hubs
- Apache RocketMQ
3、如何使用
- pom添加依赖 spring-cloud-stream-binder-kafka
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>stream-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>stream-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
</properties>
<dependencyManagement>