springBoot集成mqtt协议+activemq消息中间件

1:maven导入jar包

		
            org.eclipse.paho
            org.eclipse.paho.client.mqttv3
            1.1.1
        

2:代码

package com.wyait.web.wyaitweb.controller;

import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wyait.utils.MqttPushCallback;

/**
 * 创建一个MQTT客户端
 * @author wunaozai
 * @date 2018-08-22
 */
public class MqttPushClient {

    private static final Logger log = LoggerFactory.getLogger(MqttPushClient.class);
    public static String MQTT_HOST = "tcp://127.0.0.1:1883";
    public static String MQTT_CLIENTID = "client_id";
    public static String MQTT_USERNAME = "admin";
    public static String MQTT_PASSWORD = "admin";
    public static int MQTT_TIMEOUT = 10;
    public static int MQTT_KEEPALIVE = 10;

    private MqttClient client;
    private static volatile MqttPushClient mqttClient = null;
    public static MqttPushClient getInstance() {
        if(mqttClient == null) {
            synchronized (MqttPushClient.class) {
                if(mqttClient == null) {
                    mqttClient = new MqttPushClient();
                }
            }
        }
        return mqttClient;
    }

    public MqttPushClient() {
        log.info("Connect MQTT: " + this);
        connect();
    }

    public void connect() {
        try {
            client = new MqttClient(MQTT_HOST, MQTT_CLIENTID, new MemoryPersistence());
            MqttConnectOptions option = new MqttConnectOptions();
            option.setCleanSession(false);
            option.setUserName(MQTT_USERNAME);
            option.setPassword(MQTT_PASSWORD.toCharArray());
            option.setConnectionTimeout(MQTT_TIMEOUT);
            option.setKeepAliveInterval(MQTT_KEEPALIVE);
            option.setAutomaticReconnect(true);
            try {
                client.setCallback(new MqttPushCallback());
                client.connect(option);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 发布主题,用于通知
* 默认qos为1 非持久化 * @param topic * @param data */ public void publish(String topic, String data) { publish(topic, data, 1, false); } /** * 发布 * @param topic * @param data * @param qos * @param retained */ public void publish(String topic, String data, int qos, boolean retained) { MqttMessage message = new MqttMessage(); message.setQos(qos); message.setRetained(retained); message.setPayload(data.getBytes()); MqttTopic mqttTopic = client.getTopic(topic); if(null == mqttTopic) { log.error("Topic Not Exist"); } MqttDeliveryToken token; try { token = mqttTopic.publish(message); token.waitForCompletion(); } catch (Exception e) { e.printStackTrace(); } } /** * 订阅某个主题 qos默认为1 * @param topic */ public void subscribe(String topic) { subscribe(topic, 2); } /** * 订阅某个主题 * @param topic * @param qos */ public void subscribe(String topic, int qos) { try { client.subscribe(topic, qos); } catch (Exception e) { e.printStackTrace(); } } }
3:回调代码
package wyait.utils;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MQTT 推送回调
 * @author wunaozai
 * @date 2018-08-22
 */
public class MqttPushCallback implements MqttCallback {

    private static final Logger log = LoggerFactory.getLogger(MqttPushCallback.class);

    @Override
    public void connectionLost(Throwable cause) {
        log.info("断开连接,建议重连" + this);
        //断开连接,建议重连
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info(token.isComplete() + "");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("Topic: " + topic);
        log.info("Message: " + new String(message.getPayload()));
    }

}

4:

@Controller
@Slf4j
@RequestMapping(value = "mqqt")
@Api(tags = "MqqtController", description = "mqqt发布消息测试")
public class MqqtController {

    private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd");

    @ApiOperation(value = "发布")
    @GetMapping(value = "client")
    @ResponseBody
    public static void publish(){
        MqttPushClient mqttPushClient = new MqttPushClient();
        mqttPushClient.publish("topic", "消息", 2, false);
    }
}

你可能感兴趣的:(springBoot)