什么是Spring Cloud Stream
一个用于构建消息驱动的微服务的框架
应用程序通过 inputs 或者 outputs 来与 Spring Cloud Stream 中binder 交互,通过我们配置来 binding ,而 Spring Cloud Stream 的 binder 负责与中间件交互。所以,我们只需要搞清楚如何与 Spring Cloud Stream 交互就可以方便使用消息驱动的方式
Spring Cloud Stream编程模型
- Destination Binder(目标绑定器)
- 与消息中间件通信的组件
- Destination Bindings(目标绑定)
- Binding是连接应用程序与消息中间件的桥梁,用于消息的消费和生产,有Binder创建
- Message(消息)
微服务集成了Stream,Stream的Destination Binder创建了两个Binding,左边的Binding连接Rabbit MQ,右边的MQ连接Kafka。
左边的Binding从Rabbit MQ处消费消息,然后经过Application处代码的处理,把处理结果传输给Kafka。【从Rabbit MQ处消费消息,然后经过处理,生产到Kafka】
使用Spring Cloud Stream 实现消息收发
编写生产者
添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency>
注意groupId为com.alibaba.cloud,而不是org.springframework.cloud
添加注解
在启动类上添加@EnableBinding注解,其中Source用来发送消息
@SpringBootApplication
@EnableBinding(Source.class)
public class Study01Application {
public static void main(String[] args) {
SpringApplication.run(Study01Application.class, args);
}
}
添加配置
rocketmq.binder.name-server RocketMQ控制台地址
bindings.output.destination 指定topic
spring:
cloud:
stream:
rocketmq:
binder:
name-server: 127.0.0.1:9876
bindings:
# 生产者
output:
# 指定topic
destination: topic-stream
代码实现
注入Source接口,用来实现消息发送
MessageBuilder构建消息体
@Autowired
private Source source;
@GetMapping("test-stream")
public String testStream() {
this.source.output()
.send(
MessageBuilder
.withPayload("消息体")
.build()
);
return "testStream";
}
控制台查看
启动项目,请求之后,可以在RocketMQ控制台-消息页面看见topic为topic-stream的消息