如何调度具有MqttCallback的messageArrived方法的java代码

如何调度具有MqttCallback的messageArrived方法的java代码,java,server,mqtt,Java,Server,Mqtt,我是MQTT世界的新手。我已经编写了一个代码来订阅一个主题,从主题中获取消息并将其存储在数据库中。现在我的问题是如何把这个代码放到服务器上,这样它就可以无限地接收消息。我正在尝试创建一个调度程序,但在这种情况下,我从MQTT中得到了持久性已在使用错误。我无法在每次连接时更改clientId。我的情况是固定的。是否有任何方法可以获取已为特定clientId连接的持久性对象 请帮忙。谢谢,预告 请查找mqqt的代码订阅主题和messageArrived方法以从主题获取消息 public class

我是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);
        }
    }
}
公共类AppTest{
私有MqttHandler;
公共无效doApp(){
//从conf文件中读取属性
Properties props=MqttUtil.readProperties(“MyData/app.conf”);
字符串org=props.getProperty(“org”);
String id=props.getProperty(“appid”);
字符串authmethod=props.getProperty(“key”);
字符串authtoken=props.getProperty(“令牌”);
//isSSL属性
字符串sslStr=props.getProperty(“isSSL”);
布尔isSSL=false;
如果(sslStr等于(“T”)){
isSSL=真;
}
//格式:a::
字符串clientId=“a:”+org+:“+id;
字符串serverHost=org+MqttUtil.SERVER\u后缀;
handler=新的AppMqttHandler();
connect(serverHost、clientId、authmethod、authtoken、isSSL);
//订阅设备事件
//物联网-2/类型//id//evt//fmt/
handler.subscribe(“iot-2/type/”+MqttUtil.DEFAULT\u DEVICE\u type
+“/id/+/evt/”+MqttUtil.DEFAULT_EVENT_id+“/fmt/json”,0);
}
/**
*此类实现为应用程序MqttHandler
*
*/
私有类AppMqttHandler扩展了MqttHandler{
//模式来检查事件是否来自事件的设备
Pattern=Pattern.compile(“iot-2/type/”
+MqttUtil.DEFAULT_DEVICE_TYPE+“/id/(.+)/evt/”
+MqttUtil.DEFAULT_EVENT_ID+“/fmt/json”);
DatabaseHelper dbHelper=新的DatabaseHelper();
/**
*一旦收到订阅的消息
*/
@凌驾
public void messageArrived(字符串主题,MqttMessage MqttMessage)
抛出异常{
super.messageArrived(主题,mqttMessage);
Matcher-Matcher=pattern.Matcher(主题);
if(matcher.matches()){
字符串负载=新字符串(mqttMessage.getPayload());
//以Json格式解析有效负载
JSONObject contObj=新的JSONObject(有效载荷);
系统输出
.println(“jsonObject到达AppTest:+contObj”);
//调用方法在数据库中插入数据
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();
        }

    }

}
public void connect(字符串serverHost、字符串clientId、字符串authmethod、,
字符串authtoken,布尔值(isSSL){
//检查客户端是否已连接
如果(!isMqttConnected()){
字符串connectionUri=null;
//tcp://.messaging.internetofthings.ibmcloud.com:1883
//ssl://.messaging.internetofthings.ibmcloud.com:8883
如果(isSSL){
connectionUri=“ssl://”+serverHost+:“+DEFAULT\u ssl\u端口;
}否则{
connectionUri=“tcp://”+serverHost+:“+DEFAULT\u tcp\u端口;
}
如果(客户端!=null){
试一试{
client.disconnect();
}捕获(MqttException e){
e、 printStackTrace();
}
client=null;
}
试一试{
client=新的MqttClient(connectionUri,clientId);
}捕获(MqttException e){
e、 printStackTrace();
}
client.setCallback(this);
//创建MqttConnectOptions并设置清除会话标志
MqttConnectOptions=new MqttConnectOptions();
options.setCleansion(false);
options.setUserName(authmethod);
options.setPassword(authtoken.toCharArray());
//如果使用SSL,不要忘记使用TLSv1.2
如果(isSSL){
java.util.Properties sslClientProps=new java.util.Properties();
sslClientProps.setProperty(“com.ibm.ssl.protocol”、“TLSv1.2”);
选项。设置SLProperties(sslClientProps);
}
试一试{
//连接
client.connect(选项);
System.out.println(“连接到”+connectionUri);
}捕获(MqttException e){
e、 printStackTrace();
}
}
}

您只需启动mqtt客户端,然后订阅,它将一直运行,直到停止,并且每次传递新消息时都会调用
messagearrized
方法,无需继续重新连接。错误是因为您试图同时启动多个客户端time@hardillb谢谢你的评论。是的,与我想做的完全相同,但我不知道如何将其放在服务器上并启动它。我已尝试对其进行调度,但失败。以及它停止后将如何重新启动。请提供一些示例帮助。我现在正在使用bluemix服务器。您只需启动mqtt客户端,然后订阅,它将一直运行,直到停止并且<代码>messageArrived方法将在每次传递新邮件时调用,无需继续重新连接。错误是因为您试图同时启动多个客户端time@hardillb谢谢你的评论。是的,和我想做的完全一样,但我不知道如何把它放到服务器上并启动它。我已经试过了导出它,但失败。以及它停止后将如何重新启动。请提供一些示例帮助。我正在使用bluemix服务器。