Spring Cloud Alibaba 异步通信 - RocketMQ 自定义 Binding

概述

在实际生产中,我们需要发布和订阅的消息可能不止一种 Topic ,故此时就需要使用自定义 Binding 来帮我们实现多 Topic 的发布和订阅功能

生产者

自定义 Output 接口,代码如下:

  1. public interface MySource {
  2. @Output("output1")
  3. MessageChannel output1();
  4. @Output("output2")
  5. MessageChannel output2();
  6. }

发布消息的案例代码如下:

  1. @Autowired
  2. private MySource source;
  3. public void send(String msg) throws Exception {
  4. source.output1().send(MessageBuilder.withPayload(msg).build());
  5. }

消费者

自定义 Input 接口,代码如下:

  1. public interface MySink {
  2. @Input("input1")
  3. SubscribableChannel input1();
  4. @Input("input2")
  5. SubscribableChannel input2();
  6. @Input("input3")
  7. SubscribableChannel input3();
  8. @Input("input4")
  9. SubscribableChannel input4();
  10. }

接收消息的案例代码如下:

  1. @StreamListener("input1")
  2. public void receiveInput1(String receiveMsg) {
  3. System.out.println("input1 receive: " + receiveMsg);
  4. }

Application

配置 Input 和 Output 的 Binding 信息并配合 @EnableBinding 注解使其生效,代码如下:

  1. @SpringBootApplication
  2. @EnableBinding({ MySource.class, MySink.class })
  3. public class RocketMQApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(RocketMQApplication.class, args);
  6. }
  7. }

application.yml

生产者

  1. spring:
  2. application:
  3. name: rocketmq-provider
  4. cloud:
  5. stream:
  6. rocketmq:
  7. binder:
  8. namesrv-addr: 192.168.10.149:9876
  9. bindings:
  10. output1: {destination: test-topic1, content-type: application/json}
  11. output2: {destination: test-topic2, content-type: application/json}

消费者

  1. spring:
  2. application:
  3. name: rocketmq-consumer
  4. cloud:
  5. stream:
  6. rocketmq:
  7. binder:
  8. namesrv-addr: 192.168.10.149:9876
  9. bindings:
  10. input: {consumer.orderly: true}
  11. bindings:
  12. input1: {destination: test-topic1, content-type: text/plain, group: test-group, consumer.maxAttempts: 1}
  13. input2: {destination: test-topic1, content-type: text/plain, group: test-group, consumer.maxAttempts: 1}
  14. input3: {destination: test-topic2, content-type: text/plain, group: test-group, consumer.maxAttempts: 1}
  15. input4: {destination: test-topic2, content-type: text/plain, group: test-group, consumer.maxAttempts: 1}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧浩海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值