开发者社区> 问答> 正文

通过代码,如何使用多个MessageHandler 去处理消息?

通过代码,如何使用多个MessageHandler 去处理消息?

展开
收起
vncamyi27xznk 2021-11-11 11:02:34 488 0
1 条回答
写回答
取消 提交回答
  • "SubscribableChannel messageChannel = new DirectChannel(); messageChannel.subscribe(msg -> { System.out.println(""receive1: "" + msg.getPayload()); }); messageChannel.subscribe(msg -> { System.out.println(""receive2: "" + msg.getPayload()); }); messageChannel.send(MessageBuilder.withPayload(""msg from alibaba"").build()); messageChannel.send(MessageBuilder.withPayload(""msg from alibaba"").build()); 由于 DirectChannel 内部的消息分发器是 UnicastingDispatcher 单播的方式,并且采用轮询的负载均衡策略,所以这里两次的消费分别对应这两个 MessageHandler。控制台打印出: receive1: msg from alibaba receive2: msg from alibaba 既然存在单播的消息分发器 UnicastingDispatcher,必然也会存在广播的消息分发 器,那就是 BroadcastingDispatcher,它被 PublishSubscribeChannel 这个消息通道 所使用。广播消息分发器会把消息分发给所有的 MessageHandler: SubscribableChannel messageChannel = new PublishSubscribeChannel(); messageChannel.subscribe(msg -> { System.out.println(""receive1: "" + msg.getPayload()); }); messageChannel.subscribe(msg -> { System.out.println(""receive2: "" + msg.getPayload()); }); messageChannel.send(MessageBuilder.withPayload(""msg from alibaba"").build()); messageChannel.send(MessageBuilder.withPayload(""msg from alibaba"").build()); 发送两个消息,都被所有的 MessageHandler 所消费。控制台打印: receive1: msg from alibaba receive2: msg from alibaba receive1: msg from alibaba receive2: msg from alibaba

    这本电子书收录开发者藏经阁,下载连接:https://developer.aliyun.com/topic/download?id=1216"

    2021-11-11 19:08:58
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
fibjs 模块重构从回调到协程--陈垒 立即下载
函数计算最佳实践:快速开发一个分布式 Puppeteer 网页截图服务 立即下载
fibjs 模块重构从回调到协程 立即下载