如何安排具有MqttCallback的messageArrived方法的java代码

时间:2017-01-27 09:51:05

标签: java server mqtt

我是MQTT世界的新手。我编写了一个代码来订阅主题并从主题获取消息并将其存储在数据库中。现在我的问题是如何将此代码放在服务器上,以便它将继续无限地接收消息。我正在尝试创建一个调度程序,但在这种情况下,我正在使用MQTT中的持久性使用错误。每次连接时我都无法更改clientId。在我的情况下,它是固定的。有没有办法获得已经为特定clientId连接的持久性对象?

请帮忙。谢谢并提前。

请找到mqqt的代码订阅主题和messageArrived方法以从主题获取消息

public class AppTest {
private MqttHandler handler;

public void doApp() {
    // Read properties from the conf file
    Properties props = MqttUtil.readProperties("MyData/app.conf");

    String org = props.getProperty("org");
    String id = props.getProperty("appid");
    String authmethod = props.getProperty("key");
    String authtoken = props.getProperty("token");
    // isSSL property
    String sslStr = props.getProperty("isSSL");
    boolean isSSL = false;
    if (sslStr.equals("T")) {
        isSSL = true;
    }

    // Format: a:<orgid>:<app-id>
    String clientId = "a:" + org + ":" + id;
    String serverHost = org + MqttUtil.SERVER_SUFFIX;

    handler = new AppMqttHandler();
    handler.connect(serverHost, clientId, authmethod, authtoken, isSSL);

    // Subscribe Device Events
    // iot-2/type/<type-id>/id/<device-id>/evt/<event-id>/fmt/<format-id>
    handler.subscribe("iot-2/type/" + MqttUtil.DEFAULT_DEVICE_TYPE
            + "/id/+/evt/" + MqttUtil.DEFAULT_EVENT_ID + "/fmt/json", 0);
}

/**
 * This class implements as the application MqttHandler
 *
 */
private class AppMqttHandler extends MqttHandler {

    // Pattern to check whether the events comes from a device for an event
    Pattern pattern = Pattern.compile("iot-2/type/"
            + MqttUtil.DEFAULT_DEVICE_TYPE + "/id/(.+)/evt/"
            + MqttUtil.DEFAULT_EVENT_ID + "/fmt/json");
    DatabaseHelper dbHelper = new DatabaseHelper();

    /**
     * Once a subscribed message is received
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage)
            throws Exception {
        super.messageArrived(topic, mqttMessage);

        Matcher matcher = pattern.matcher(topic);
        if (matcher.matches()) {
            String payload = new String(mqttMessage.getPayload());

            // Parse the payload in Json Format
            JSONObject contObj = new JSONObject(payload);
            System.out
                    .println("jsonObject arrived in AppTest : " + contObj);
            // Call method to insert data in database
            dbHelper.insertIntoDB(contObj);
        }
    }
}

连接客户端的代码

public void connect(String serverHost, String clientId, String authmethod,
        String authtoken, boolean isSSL) {
    // check if client is already connected
    if (!isMqttConnected()) {
        String connectionUri = null;

        //tcp://<org-id>.messaging.internetofthings.ibmcloud.com:1883
        //ssl://<org-id>.messaging.internetofthings.ibmcloud.com:8883
        if (isSSL) {
            connectionUri = "ssl://" + serverHost + ":" + DEFAULT_SSL_PORT;
        } else {
            connectionUri = "tcp://" + serverHost + ":" + DEFAULT_TCP_PORT;
        }

        if (client != null) {
            try {
                client.disconnect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
            client = null;
        }

        try {
            client = new MqttClient(connectionUri, clientId);
        } catch (MqttException e) {
            e.printStackTrace();
        }

        client.setCallback(this);

        // create MqttConnectOptions and set the clean session flag
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);

        options.setUserName(authmethod);
        options.setPassword(authtoken.toCharArray());

        //If SSL is used, do not forget to use TLSv1.2
        if (isSSL) {
            java.util.Properties sslClientProps = new java.util.Properties();
            sslClientProps.setProperty("com.ibm.ssl.protocol", "TLSv1.2");
            options.setSSLProperties(sslClientProps);
        }

        try {
            // connect
            client.connect(options);
            System.out.println("Connected to " + connectionUri);
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

}

0 个答案:

没有答案