EMQ的安装以及MQTT的简单使用

EMQ的安装

环境:

CentOS 7 64位

emqttd-centos7-v2.3.6.zip

Erlang    //由于emqttd是用Erlang语言编写的,所以,在Linux下安装时,需要先安装Erlang

 

安装Erlang命令 #sudo yum -y install make gcc gcc-c++ kernel-devel m4 ncurses-devel openssl-devel

EMQ的安装

安装命令:

# mkdir emq

# cd emq

# wget http://emqtt.com/static/brokers/emqttd-centos7-v2.3.6.zip

# unzip emqttd-centos7-v2.3.6.zip

# ls

 

EMQ启动

方式一:

# cd emqttd

# ./bin/emqttd console //会在控制台打印日志 Ctrl+c结束

方式二:

# ./bin/emqttd start //不会在控制台打印日志

# ./bin/emqttd status

# ./bin/emqttd stop

EMQ的安装以及MQTT的简单使用_第1张图片

注意:EMQ中有两个端口18083和1883需要打开。

MQTT的使用

此处MQTT是在SpringBoot中使用的,如图

EMQ的安装以及MQTT的简单使用_第2张图片

消息发送方

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @author zhangs
 */
public class PublishMessage {
    private static int QOS = 1;
    /**
     * 注:此处的TCP端口默认是1883
     */
    private static String HOST = "tcp://192.168.230.129:1883";
    private static String userName = "admin";
    private static String password = "public";

    private static MqttClient connect(String clientId, String userName, String password) throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(10);
        options.setKeepAliveInterval(20);

        MqttClient client = new MqttClient(HOST, clientId, persistence);
        client.setCallback(new PushCallback());
        client.connect(options);
        return client;
    }

    private static void publish(MqttClient client, String msg, String topic) throws MqttException {
        MqttMessage message = new MqttMessage(msg.getBytes());
        message.setQos(QOS);
        message.setRetained(false);
        client.publish(topic, message);
    }

    public static void start(String msg) throws MqttException {
        /*String msg = "Hello !";*/
        String clientId = "ServerId_01";
        String topic = "MQTT_TOPIC";

        MqttClient client = connect(clientId, userName, password);
        if (client != null) {
            publish(client, msg, topic);
            System.out.println("Start-----Public Message:" + msg);
        }
        if (client != null) {
            client.disconnect();
        }
    }
}
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MQTTServerController {

    @RequestMapping("/")
    public String sayHello() {
        return "Hello !";
    }

    @RequestMapping("/send")
    public void send(String msg) throws MqttException {
        PublishMessage.start(msg);
    }
}

 

消息接收方

 

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @author zhangs
 */
public class ReceiveMessage {
    private static int QOS = 1;
    /**
     * 注:此处的TCP端口默认是1883
     */
    private static String HOST = "tcp://192.168.230.129:1883";
    private static String userName = "admin";
    private static String password = "public";

    private static MqttClient connect(String clientId) throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(password.toCharArray());
        options.setKeepAliveInterval(20);
        options.setConnectionTimeout(10);

        MqttClient client = new MqttClient(HOST, clientId, persistence);
        client.setCallback(new PushCallback());
        client.connect(options);
        return client;
    }

    public static void receive(MqttClient client, String topic) throws MqttException {
        int[] Qos = {QOS};
        String[] topics = {topic};
        client.subscribe(topics, Qos);
    }

    public static void start() throws MqttException {
        String clientId = "ClientId_01";
        String topic = "MQTT_TOPIC";

        MqttClient client = connect(clientId);
        if (client != null) {
            receive(client, topic);
        }
    }
}

回调类

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

/**
 * 发布消息的回调类
 *
 * 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。
 * 每个客户机标识都需要一个回调实例。在此示例中,构造函数传递客户机标识以另存为实例数据。
 * 在回调中,将它用来标识已经启动了该回调的哪个实例。
 * 必须在回调类中实现三个方法:
 *
 *  public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。
 *
 *  public void connectionLost(Throwable cause)在断开连接时调用。
 *
 *  public void deliveryComplete(MqttDeliveryToken token))
 *  接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。
 *  由 MqttClient.connect 激活此回调。
 * @author zhangs
 */

public class PushCallback implements MqttCallback {
    @Override
    public void connectionLost(Throwable throwable) {
        /**
         * 连接丢失后,一般在这里面进行重连
         */
        System.out.println("连接断开,可以做重连");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
        System.out.println("Client 接收消息主题 : " + topic);
        System.out.println("Client 接收消息Qos : " + message.getQos());
        System.out.println("Client 接收消息内容 : " + new String(message.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }
}

注:服务连接的TCP端口是1883。两个服务订阅的主题一样即可。

启动以上两个服务,访问http://localhost:8081/send?msg=深圳市

server端

EMQ的安装以及MQTT的简单使用_第3张图片

client端

EMQ的安装以及MQTT的简单使用_第4张图片

GitHub:https://github.com/MrZhangsGit/SpringCloudStudy

你可能感兴趣的:(java笔记)