为什么会用Spring Cloud Stream去做基于消息通信呢???
好处:虽说Spring Boot对Kafka、RabbitMQ、RocketMQ等支持的比较好,但是可能还是需要按照对应规则去写对应代码。而Spring Cloud Stream可以做到基于配置提供通信。
缺点:Spring Cloud Stream只支持topic-subsriber订阅模式,但是对于我目前的系统来说,已经满足了。我的需求:只要一个服务提供消息,另一个服务能够及时处理就行。
1、生产消息的中间服务
1.1、基础依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
1.2、相关配置以及代码
1)定义消息通道
2)提供一个发送的rest
3)yml配置
基础的消息中间件信息
处理哪些通道信息(我上面只展示了一个通道)
4)发送
2、1、接收消息的服务
2.1、基础依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
2.2 、相关配置及代码
1)接收消息的代码
2)yml配置
基础的消息中间件信息
收具体某个通道的消息
注意:
1、如果接收相同渠道的服务节点有多个,那么会自动进行负载,一般是采用轮询的策略
2、接收方yml配置中的分组名,是每个通道配置对应的分组名
3、我的系统采用的消息中间件是RabbitMQ,支持很好的等价替换其他中间件
4、默认会提供重试机制,如果接收消息出现异常,会进行重试