Mqtt工具

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.UUID;

@Slf4j
public class MqttUtil {

    public static interface MqttSubscribeCallback{
        void msgNotify(String topic,JSONObject msg);
    }

    private static MqttConnectOptions createMqttConnectOptions(String username,String password) {
        // MQTT的连接设置
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(true);
        if (username != null && !username.trim().isEmpty()) {
            // 设置连接的用户名
            options.setUserName(username);
        }
        if (password != null && !password.trim().isEmpty()) {
            // 设置连接的密码
            options.setPassword(password.trim().toCharArray());
        }
        // 设置超时时间 单位为秒
        options.setConnectionTimeout(1000);
        // 设置会话心跳时间 单位为秒 服务器会每隔90秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
        options.setKeepAliveInterval(90);
        options.setAutomaticReconnect(true);
        return options;
    }

    public static MqttClient createMqttClient(String mqttUrl) {
        try {
            // HOST_MQ为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
            MqttClient client = new MqttClient(mqttUrl, UUID.randomUUID().toString(), new MemoryPersistence());
            return client;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建客户端异常", e);
            return null;
        }
    }

    public static boolean connent(MqttClient client,String username,String password,MqttSubscribeCallback callback,String... topic) {
        try {
            MqttConnectOptions options = createMqttConnectOptions(username,password);
            subscribe(client,callback,topic);
            client.connect(options);
            System.out.println("MQTT连接成功"+username+">"+password);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean subscribe(MqttClient client,MqttSubscribeCallback callback, String... topic) {
        // 设置回调
        client.setCallback(new MqttCallbackExtended() {
            public void connectComplete(boolean reconnect, String serverURI) {
                try {
                    //client.subscribe(topics, qos);
                    client.subscribe(topic);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("连接异常",e);
                }
            }

            public void connectionLost(Throwable cause) {
                cause.printStackTrace();
                log.error("连接丢失",cause);
                try {
                    client.reconnect();
                } catch (MqttException e) {
                }
            }

            public void deliveryComplete(IMqttDeliveryToken token) {
            }

            public void messageArrived(String topic, MqttMessage message) {
                try {
                    System.out.println(topic+"MQTT收到消息"+message);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String msg = message.toString();
                            JSONObject json = JSONObject.parseObject(msg);
                            callback.msgNotify(topic,json);
                        }
                    }).start();
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("消费消息异常",e);
                }
            }
        });
        System.out.println("MQTT设置回调成功"+ Arrays.toString(topic));
        return true;
    }

    public static boolean publish(MqttClient client, String topic, String message) {
        if (client == null) {
            return false;
        }
        if (!client.isConnected()) {
            try {
                client.reconnect();
            } catch (MqttException e) {
            }
        }
        if (client.isConnected()) {
            try {
                client.publish(topic, new MqttMessage(message.getBytes(StandardCharsets.UTF_8)));
                return true;
            } catch (MqttException e) {
                log.error("发送消息异常", e);
                return false;
            }
        } else {
            return false;
        }
    }
}

使用:

        String[] mqttTopic=new String[]{"test/user/" + userId};
        MqttClient mqttClient = MqttUtil.createMqttClient(API.mqttUrl);
        MqttUtil.connent(mqttClient, API.mqttAccount, API.mqttPassword,new MqttUtil.MqttSubscribeCallback() {
            @Override
            public void msgNotify(String topic, JSONObject msg) {
                mqttMsg(msg);
            }
        },mqttTopic);

你可能感兴趣的:(JavaEE,java,mqtt)