RabbitMQ MQTT适配器和Paho MQTT客户端

时间:2018-03-22 11:44:21

标签: rabbitmq mqtt

我正在使用RabbitMQ MQTT适配器和Paho MQTT客户端。

RabbitMQ版本:{rabbitmq_mqtt,"RabbitMQ MQTT Adapter","3.2.1"} Paho MQTT客户端版本:

 <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
        <version>RELEASE</version>
    </dependency>

请参阅内联代码。

我试图了解订阅者队列是否可以持久而没有到期时间。如果消息也可以持久。 正如我从RabbitMQ文档中所理解的,每次订阅者订阅主题时 RabbitMQ将使用以下命名约定创建一个队列:

mqtt-subscription-<ClientName>qos<ClientQOS>

此队列有一个到期时间,如何创建没有到期时间的队列?我可以将此队列到期时间更改为无限时间吗? 至于现在我每次运行这个命令:“service rabbitmq-server restart”

队列中的消息被删除。

我该怎样防止这种情况?有没有办法可以在重启后将消息保留在队列中?

在RabbitMQ管理界面中,我可以在“发布消息”下看到 - &gt; “交付模式:”可以是“2持久”。 如果我使用管理UI发布传递模式= 2-persistent的消息。服务重启后,消息将在队列中。

如何使用Paho MQTT Client实现相同目标?

// Heavily based on RabbitMQ MQTT adapter test case code!

// first, import the RabbitMQ Java client
// and the Paho MQTT client classes, plus any other
// requirements

import com.rabbitmq.client.*;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.internal.NetworkModule;
import org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule;
// import org.eclipse.paho.client.mqttv3.internal.trace.Trace;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttOutputStream;
import org.eclipse.paho.client.mqttv3.internal.wire.MqttPublish;

import javax.net.SocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.*;

/***
 *  MQTT v3.1 tests
 *  TODO: synchronise access to variables
 */

public class MqttTestClean implements MqttCallback {

    // setup some variables which define where the MQTT broker is
    private final String host = "0.0.0.0";
    private final int port = 1883;
    private final String brokerUrl = "tcp://" + host + ":" + port;
    private String clientId;
    private String clientId3;
    private MqttClient client;
    private MqttClient client3;
    private MqttConnectOptions conOpt;
    private ArrayList<MqttMessage> receivedMessages;

    // specify a message payload - doesn't matter what this says, but since MQTT expects a byte array
    // we convert it from string to byte array here
    private final byte[] payload = "This payload was published on MQTT and read using AMQP.".getBytes();

    // specify the topic to be used
    private final String topic = "topic/proxy/1.0.0/Report/*";

    private int testDelay = 2000;
    private long lastReceipt;
    private boolean expectConnectionFailure;

    private ConnectionFactory connectionFactory;
    private Connection conn;
    private Channel ch;

    // override 10s limit
    private class MyConnOpts extends MqttConnectOptions {
        private int keepAliveInterval = 60;
        @Override
        public void setKeepAliveInterval(int keepAliveInterval) {
            this.keepAliveInterval = keepAliveInterval;
        }
        @Override
        public int getKeepAliveInterval() {
            return keepAliveInterval;
        }
    }

    public void setUpMqtt() throws MqttException {
        clientId = getClass().getSimpleName() + ((int) (10000*Math.random()));
        client = new MqttClient(brokerUrl, clientId);
        conOpt = new MyConnOpts();
        setConOpts(conOpt);
        receivedMessages = new ArrayList<MqttMessage>();
        expectConnectionFailure = false;
    }

    public  void tearDownMqtt() throws MqttException {
        try {
            client.disconnect();
        } catch (Exception _) {}
    }

    private void setUpAmqp() throws Exception {
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(host);
        conn = connectionFactory.newConnection();
        ch = conn.createChannel();
    }

    private void tearDownAmqp() throws IOException {
        conn.close();
    }

    private void setConOpts(MqttConnectOptions conOpts) {
        conOpts.setCleanSession(true);
        conOpts.setKeepAliveInterval(60);
    }

    private void publish(MqttClient client, String topicName, int qos, byte[] payload) throws MqttException {
        MqttTopic topic = client.getTopic(topicName);
        MqttMessage message = new MqttMessage(payload);
        message.setQos(qos);
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
    }

    public void connectionLost(Throwable cause) {
        if (!expectConnectionFailure)
            System.out.println("Connection unexpectedly lost");
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        lastReceipt = System.currentTimeMillis();
        System.out.println("-------------------------------------------------");
        System.out.println("------------------"  + lastReceipt + "-------------------------------");
        System.out.println("------------------"  + message.toString() + "-------------------------------");
        receivedMessages.add(message);
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
    }

    public void run() {
        try {

            setUpMqtt(); // initialise the MQTT connection
            setUpAmqp(); // initialise the AMQP connection

            connect();

            //String queue = ch.queueDeclare().getQueue();
            // String queue = ch.queueDeclare("mqtt-subscription-Snabel-3qos1", true, false, false, null).getQueue();
            //ch.queueBind(queue, "amq.topic", "sci-topic.sc.proxy_1393.1.0.0.ApReport.*"/*topic*/);

            client.connect(conOpt);
            publish(client, "topic/proxy/1.0.0/Report/123456789",1, payload); // publish the MQTT message
            client.disconnect();
            Thread.sleep(testDelay);

            tearDownAmqp(); // cleanup AMQP resources
            tearDownMqtt(); // cleanup MQTT resources*/
            disConnect();

        } catch (Exception mqe) {
            mqe.printStackTrace();
        }
    }


    private void connect() throws Exception {
        clientId3 = "Test-3";
        client3 = new MqttClient(brokerUrl, clientId3);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(false);

        client3.connect(connOpts);
        client3.setCallback(this);
        client3.subscribe(topic);

        if(!client3.isConnected()){

            System.out.println("Not Connected");
            return;
        }
        System.out.println("Connected");
    }

    private void disConnect() throws Exception {
        try {
            client3.disconnect();
        } catch (Exception _) {}
    }

    public static void main(String[] args) {
        MqttTest mqt = new MqttTest();
        mqt.run();
    }
}