Solon v2.7.5

使用分布式事件 - 多通道示例

</> markdown

生态 / Solon Cloud Event [传送]

1、情况简介

所谓多通道,即多个插件同时使用。比如用 mqtt 做物联网消息的处理,再用 rabbitmq 做为业务系统的消息处理。这是一直有的特性,却忘了完善资料,罪过。

2、引入 maven 包

<dependencies>
    <dependency>
        <groupId>org.noear</groupId>
        <artifactId>mqtt-solon-cloud-plugin</artifactId>
    </dependency>

    <dependency>
        <groupId>org.noear</groupId>
        <artifactId>rabbitmq-solon-cloud-plugin</artifactId>
    </dependency>
</dependencies>

3、添加应用配置示例

# mqtt 做为默认通道 //不需要指定 event.channel
solon.cloud.mqtt:
  server: "tcp://localhost:41883"   #mqtt服务地址

# rabbitmq 做为 biz 通道 //指定了 event.channel
solon.cloud.rabbitmq:
  server: localhost:5672   #rabbitmq 服务地址
  username: root           #rabbitmq 链接账号
  password: 123456         #rabbitmq 链接密码
  event:
    channel: "biz"

4、添加定阅与发送的代码示例

订阅消息

//订阅 biz 通道的消息
@CloudEvent(value = "hello.biz", channel = "biz")
public class EVENT_hello_demo2 implements CloudEventHandler {
    @Override
    public boolean handle(Event event) throws Throwable {
        System.out.println(LocalDateTime.now() + ONode.stringify(event));

        return event.times() > 2;
    }
}

//订阅 默认 通道的消息(不指定通道,即为默认)
@CloudEvent("hello.mtt")
public class EVENT_hello_demo2 implements CloudEventHandler {
    @Override
    public boolean handle(Event event) throws Throwable {
        System.out.println(LocalDateTime.now() + ONode.stringify(event));

        return event.times() > 2;
    }
}

发送消息

//发送 biz 通道的消息
Event event = new Event("hello.biz", msg).channel("biz");
return CloudClient.event().publish(event);

//发送 默认 通道的消息(不指定通道,即为默认)
Event event = new Event("hello.mtt", msg).qos(1).retained(true);
return CloudClient.event().publish(event);

5、使用时有什么区别?

就是多了 channel 需要指定,没有指定时则为默认。

6、示例源码

https://gitee.com/noear/solon-examples/tree/main/9.Solon-Cloud/demo9039-event_multi_channel2