如何使用Java客户端同时发布MQTT消息?

时间:2019-05-08 10:43:43

标签: java mqtt iot paho hivemq

我正在尝试使用5个Java客户端同时发布MQTT消息,以便每个Java客户端同时将特定主题上的1000条消息同时发布到MQTT代理(HIVEMQ)

我打开了多个线程,每个线程创建一个mqtt客户端并使用ssl连接到代理,并尝试同时发布1000条消息,正在发送消息,但所有连接都无法成功代理,并且我一直在获取异常< / p>

Client is not connected (32104)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:31)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms.sendNoWait(ClientComms.java:199)
    at org.eclipse.paho.client.mqttv3.MqttAsyncClient.publish(MqttAsyncClient.java:1355)
    at org.eclipse.paho.client.mqttv3.MqttClient.publish(MqttClient.java:583)
    at org.eclipse.paho.client.mqttv3.MqttClient.publish(MqttClient.java:575)
    at com.test.MqttPublishSample.publishMessages(MqttPublishSample.java:122)
    at com.test.MqttPublishSample.lambda$start$0(MqttPublishSample.java:74)
    at java.base/java.lang.Thread.run(Thread.java:834)
public class MqttPublishSample {

    public static void main(String... args) throws InterruptedException {

        new MqttPublishSample().start();

    }

  public void start() throws InterruptedException {


        for(int i=0;i<5;i++){

            new Thread(()->{
                MqttClient client = null;
                try {
                    client = obtainConnection();//code to obtain connection using MqttClient
                    publishMessages(client);//code to publish message using simple for loop 

                } catch (MqttException e) {
                    e.printStackTrace();
                }

            }).start();
        }
    }
public MqttClient obtainConnection() throws MqttException {
        String clientId = "sslTestClient"+ThreadLocalRandom.current().nextInt(0,5);
        MqttClient client = null;
        try {
            client = new MqttClient("ssl://localhost:8883", clientId, new MemoryPersistence());
        } catch (MqttException e) {
            e.printStackTrace();
        }

        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName("user1");
        mqttConnectOptions.setPassword("pass1".toCharArray());
        try {
            mqttConnectOptions.setSocketFactory(getTruststoreFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("connecting...");
        client.connect(mqttConnectOptions);
        return client;
    }

我希望所有客户端都能成功连接到代理并发布消息

1 个答案:

答案 0 :(得分:1)

可能是您在线程上使用了相同的clientID,因此服务器将断开重复的连接。当您使用LocalThreadRandom时,有可能发生冲突(因为只有5个选择,所以冲突很大)。您可以使用generateClientId()提供的唯一标识符,也可以在线程之间共享一个跟踪它们的方法。