mqtt-emqx:利用主题【<topicName>】进行广播消费

9 篇文章 0 订阅
  • 广播订阅
    • <topicName>
  • 集群订阅
    • $queue/<topicName>
  • 分组集群订阅
    • $share/<groupName>/<topicName>

下面测试【广播订阅:<topicName>】这种情况
【pom.xml】

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.3.12.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.2.2</version>
</dependency>
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.49</version>
</dependency>

【MyDemo2IMqttMessageListener.java】

package com.chz.myMqttV3.demo2;

@Slf4j
public class MyDemo2IMqttMessageListener implements IMqttMessageListener
{
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        log.info("messageArrived: topic={}, message={}", topic, new String(message.getPayload()));
    }
}

【MyDemo2MqttCallback.java】

package com.chz.myMqttV3.demo2;

@Slf4j
public class MyDemo2MqttCallback implements MqttCallbackExtended {

    private MqttClient client;
    private MqttConnectOptions options;
    private String[] topics;

    public MyDemo2MqttCallback(MqttClient client, MqttConnectOptions options, String[] topics)
    {
        this.client = client;
        this.options = options;
        this.topics = topics;
    }

    @SneakyThrows
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("connectionLost", throwable);
        while (!client.isConnected()) {
            log.info("emqx重新连接....................................................");
            client.connect(options);
            Thread.sleep(1000);
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("messageArrived: topic={}, message={}", topic, new String(message.getPayload()));
    }

    @SneakyThrows
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        if( token!=null ){
            MqttMessage message = token.getMessage();
            String topic = token.getTopics()==null ? null : Arrays.asList(token.getTopics()).toString();
            String str = message==null ? null : new String(message.getPayload());
            log.info("deliveryComplete: topic={}, message={}", topic, str);
        } else {
            log.info("deliveryComplete: null");
        }
    }

    @SneakyThrows
    @Override
    public void connectComplete(boolean reconnect, String serverURI)
    {
        log.info("connectComplete: reconnect={}, serverURI={}", reconnect, serverURI);
        if( topics.length > 0 )
        {
            int[] qosArr = new int[topics.length];
            Arrays.fill(qosArr, 2);

            MyDemo2IMqttMessageListener[] listeners = new MyDemo2IMqttMessageListener[topics.length];
            Arrays.fill(listeners, new MyDemo2IMqttMessageListener());

            client.subscribe(topics, qosArr, listeners);
        }
    }
}

【MyDemo2MqttClient1Test.java】

package com.chz.myMqttV3.demo2;

public class MyDemo2MqttClient1Test
{
    public static void main(String[] args) throws UnknownHostException, MqttException, InterruptedException {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("admin");
        options.setPassword("public".toCharArray());
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(20);
        options.setKeepAliveInterval(10);

        MqttClient client = new MqttClient("tcp://192.168.44.228:1883", "MyDemo2MqttClient1Test", new MemoryPersistence());
        client.setCallback(new MyDemo2MqttCallback(client, options, new String[]{"device/#"}));
        client.connect(options);
    }
}

注意订单的是主题是【device/#】
【MyDemo2MqttClient2Test.java】

package com.chz.myMqttV3.demo2;

public class MyDemo2MqttClient2Test {

    public static void main(String[] args) throws MqttException, InterruptedException
    {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("admin");
        options.setPassword("public".toCharArray());
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(20);
        options.setKeepAliveInterval(10);

        MqttClient client = new MqttClient("tcp://192.168.44.229:1883", "MyDemo2MqttClient2Test", new MemoryPersistence());
        client.setCallback(new MyDemo2MqttCallback(client, options, new String[]{"device/#"}));
        client.connect(options);
    }
}

注意订单的是主题也是【device/#】
【MyDemo2MqttSenderTest.java】

package com.chz.myMqttV3.demo2;

public class MyDemo2MqttSenderTest {

    public static void main(String[] args) throws MqttException, InterruptedException
    {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("admin");
        options.setPassword("public".toCharArray());
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(20);
        options.setKeepAliveInterval(10);

        MqttClient client = new MqttClient("tcp://192.168.44.230:1883", "MyDemo2MqttSenderTest", new MemoryPersistence());
        client.setCallback(new MyDemo2MqttCallback(client, options, new String[]{}));
        client.connect(options);

        for( int i=0; ; i++ ){
            String topic = "device/1";
            MqttMessage mqttMessage = new MqttMessage();
            String msg = "I am MyMqttClient3Test, at node [192.168.44.230:1883]: " + i;
            mqttMessage.setPayload(msg.getBytes(StandardCharsets.UTF_8));
            client.publish(topic, mqttMessage);
            Thread.sleep(10000L);
        }
    }
}

运行【MyDemo2MqttClient1Test、MyDemo2MqttClient2Test、MyDemo2MqttSenderTest】,看运行日志:
在这里插入图片描述
在这里插入图片描述
可以看出,消费了主题【device/#】的所有client都消费到了一份数据

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陈鸿圳

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

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

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

打赏作者

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

抵扣说明:

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

余额充值