SpringCloud Stream 消息驱动
Spring Cloud Stream官方的说法是一个构建消息驱动微服务的框架。我们可以这么理解,这个Spring Cloud Stream封装了mq的玩法,统一了模型,然后屏蔽各个mq产品中间件不同,降低了我们的学习成本,不过目前只支持kafka与rabbitmq。我们的应用程序,也就是spring Application ,通过这个input 与output 这两种channel 与binder 进行交互,binder(绑定器对象)屏蔽了咱们的消息中间件产品的差异, 封装了消息中间件,可以很方便的链接中间件
我们可以看下这个Spring Cloud Stream的架构图
简单使用
消息生产者
-
创建Stream-Service
-
引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
</dependencies>
- 配置application.yml
server:
port: 7001 #服务端口
spring:
application:
name: stream_service #指定服务名
rabbitmq:
addresses: localhost
username: guest
password: guest
port: 5672
cloud:
stream:
bindings:
output:
destination: yuan11-topic #指定消息发送的目的地,在rabbitmq中,发送到一个yuan11-topic的exchange中
binders: #配置绑定器
defaultRabbit:
type: rabbit # 绑定的是rabbit
- contentType:用于指定消息的类型。具体可以参考 spring cloud stream docs
- destination:指定了消息发送的目的地,对应 RabbitMQ,会发送到 exchange 是 yuan11-topic的所有消息队列中。
- 运行启动类,查看rabbitmq 的通道,可以看到通道已经添加了
- 创建消息发送类HelloController
/**
* @title: HelloController
* @Author yuan11
* @Date: 2022/4/27 1:09
* @Version 1.0