java模拟MQTT客户端发送消息及EMQX配置

news2024/10/6 16:30:10

EMQX配置

登录地址

首先打开EMQX的管理界面,界面的地址如下,

http://192.168.1.110:18083/

规则是IP就是MQTT的IP,端口是固定的18083,输入该地址后,展示界面如下:

 然后输入用户名和密码,用户名和密码就是MQTT连接的账号和密码。

设置中文

登录系统后,界面是默认是英文的,我们需要设置为中文。点击右上角的【设置】图标,然后就可以选择中文了。

选择简体中文后,点击保存即可。

设置速率

依次按照下图的操作步骤点击,点击【管理】,点击【速率限制】,然后输入相应的参数,点击确定即可。

 EMQX 提供对接入速度、消息速度的限制,从入口处避免了系统过载,保证了系统的稳定和可预测的吞吐。

限制器类型

EMQX 使用以下几种类型的限制器来限制速率:

类型描述过载后行为
bytes_rate单个客户端每秒流入的消息的字节数大小暂停接收客户端消息
messages_rate单个客户端每秒流入的消息条数暂停接收客户端消息
max_conn_rate当前监听器每秒的连接数暂停接收新的连接

限制器可以在监听器级别上工作。例如,要为默认的TCP监听器设置限制器,可以在 emqx.conf 中按以下进行配置:

listeners.tcp.default {
  bind = "0.0.0.0:1883"
  max_conn_rate = "1000/s"
  messages_rate = "1000/s"
  bytes_rate = "1000MB/s"
}

 最大待发PUBREL数量配置

最大待发PUBREL数量配置,这个配置非常的重要,如果不配置那么我们的客户端模拟发送数据,可以达到默认的100就无法发送其它的数据了。比如我用客户端写一个DEMO,每5秒钟发送一次,一次发送200条数据,那么你在你的监听的客户端去看,它是无法收到刚才发送的200秒数据的。

客户端代码

 POM依赖如下

<!-- mqtt -->
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-mqtt</artifactId>
		</dependency>

		<!-- JSONObject对象依赖的jar包 开始 -->
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.3</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.2.3</version>
			<classifier>jdk15</classifier>
			<!-- jdk版本 -->
		</dependency>
		<!-- Json依赖架包下载结束 -->

application.properties配置文件

## MQTT##
mqtt.host=tcp://192.168.1.110:1883
mqtt.clientId=ClientId_test_0717
mqtt.userName=admin
mqtt.passWord=public
mqtt.timeout=10
mqtt.keepalive=20
mqtt.topic1=iot_demo_report

MqttConfiguration.java

package cn.renkai721.mqtt;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 1. @author renkai721@163.com
 2. @date 2023/07/17 16:40
 */
@Configuration
public class MqttConfiguration {

    private static final Logger log = LoggerFactory.getLogger(MqttConfiguration.class);
    @Value("${mqtt.host}")
    String host;
    @Value("${mqtt.username}")
    String username;
    @Value("${mqtt.password}")
    String password;
    @Value("${mqtt.clientId}")
    String clientId;
    @Value("${mqtt.timeout}")
    int timeOut;
    @Value("${mqtt.keepalive}")
    int keepAlive;
    @Value("${mqtt.topic1}")
    String topic1;

    @Bean
    public MyMQTTClient myMQTTClient() {
        MyMQTTClient myMQTTClient = new MyMQTTClient(host, username, password, clientId, timeOut, keepAlive);
        for (int i = 0; i < 10; i++) {
            try {
                myMQTTClient.connect();
                return myMQTTClient;
            } catch (MqttException e) {
                log.error("MQTT connect exception,connect time = " + i);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return myMQTTClient;
    }
    public String getTopic1() {
        return topic1;
    }

    public void setTopic1(String topic1) {
        this.topic1 = topic1;
    }


}

MqttController.java

package cn.renkai721.mqtt;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author renkai721@163.com
 * @date 2023/07/17 16:40
 */
@RestController
@EnableAsync
@RequestMapping("/sun/mqtt")
public class MqttController {

    @Autowired
    private MyMQTTClient myMQTTClient;
    @Autowired
    private MyMqttService myMqttService;

    @Value("${mqtt.topic1}")
    String topic1;


    @PostMapping("/sendMsg")
    @ResponseBody
    public String sendMsg() {
        myMqttService.sendMsg();
        return "success";
    }
}

MqttMsg.java

package cn.renkai721.mqtt;

/**
 * @author renkai721@163.com
 * @date 2023/07/17 16:40
 */
public class MqttMsg {
    private String name = "";
    private String content = "";
    private String time = "";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    @Override
    public String toString() {
        return "MqttMsg{" +
                "name='" + name + '\'' +
                ", content='" + content + '\'' +
                ", time='" + time + '\'' +
                '}';
    }
}

MyMQTTCallback.java

package cn.renkai721.mqtt;

import com.alibaba.fastjson.JSON;
import io.netty.util.CharsetUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author renkai721@163.com
 * @date 2023/07/17 16:40
 */
public class MyMQTTCallback implements MqttCallbackExtended {

    //手动注入
    private MqttConfiguration mqttConfiguration = SpringUtils.getBean(MqttConfiguration.class);

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

    private MyMQTTClient myMQTTClient;

    public MyMQTTCallback(MyMQTTClient myMQTTClient) {
        this.myMQTTClient = myMQTTClient;
    }


    /**
     * 丢失连接,可在这里做重连
     * 只会调用一次
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("mqtt connectionLost 连接断开,5S之后尝试重连: {}", throwable.getMessage());
        long reconnectTimes = 1;
        while (true) {
            try {
                if (MyMQTTClient.getClient().isConnected()) {
                    log.warn("mqtt reconnect success end  重新连接  重新订阅成功");
                    return;
                }
                reconnectTimes+=1;
                log.warn("mqtt reconnect times = {} try again...  mqtt重新连接时间 {}", reconnectTimes, reconnectTimes);
                MyMQTTClient.getClient().reconnect();
            } catch (MqttException e) {
                log.error("mqtt断连异常", e);
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
            }
        }
    }

    /**
     * @param topic
     * @param mqttMessage
     * @throws Exception
     * subscribe后得到的消息会执行到这里面
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        log.info("接收消息主题 : {},接收消息内容 : {}", topic, new String(mqttMessage.getPayload()));
        
        //你自己的业务接口
         
    }


    /**
     *连接成功后的回调 可以在这个方法执行 订阅主题  生成Bean的 MqttConfiguration方法中订阅主题 出现bug
     *重新连接后  主题也需要再次订阅  将重新订阅主题放在连接成功后的回调 比较合理
     * @param reconnect
     * @param serverURI
     */
    @Override
    public  void  connectComplete(boolean reconnect,String serverURI){
        log.info("MQTT 连接成功,连接方式:{}",reconnect?"重连":"直连");
        //订阅主题
        myMQTTClient.subscribe(mqttConfiguration.topic1, 1);
    }

    /**
     * 消息到达后
     * subscribe后,执行的回调函数
     * publish后,配送完成后回调的方法
     *
     * 
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("==========deliveryComplete={}==========", iMqttDeliveryToken.isComplete());
    }
}

MyMQTTClient.java

package cn.renkai721.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 1. @author renkai721@163.com
 2. @date 2023/07/17 16:40
 */
public class MyMQTTClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyMQTTClient.class);

    private static MqttClient client;
    private String host;
    private String username;
    private String password;
    private String clientId;
    private int timeout;
    private int keepalive;
    public MyMQTTClient(String host, String username, String password, String clientId, int timeOut, int keepAlive) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.clientId = clientId;
        this.timeout = timeOut;
        this.keepalive = keepAlive;
    }

    public static MqttClient getClient() {
        return client;
    }

    public static void setClient(MqttClient client) {
        MyMQTTClient.client = client;
    }

    /**
     * 设置mqtt连接参数
     */
    public MqttConnectOptions setMqttConnectOptions(String username, String password, int timeout, int keepalive) {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(timeout);
        options.setKeepAliveInterval(keepalive);
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        return options;
    }

    /**
     * 连接mqtt服务端,得到MqttClient连接对象
     */
    public void connect() throws MqttException {
        if (client == null) {
            client = new MqttClient(host, clientId, new MemoryPersistence());
            client.setCallback(new MyMQTTCallback(MyMQTTClient.this));
        }
        MqttConnectOptions mqttConnectOptions = setMqttConnectOptions(username, password, timeout, keepalive);
        if (!client.isConnected()) {
            client.connect(mqttConnectOptions);
        } else {
            client.disconnect();
            client.connect(mqttConnectOptions);
        }
        LOGGER.info("MQTT connect success");//未发生异常,则连接成功
    }

    /**
     * 发布,默认qos为0,非持久化
     */
    public void publish(String pushMessage, String topic) {
        publish(pushMessage, topic, 2, false);
    }

    /**
     * 发布消息
     *
     */
    public void publish(String pushMessage, String topic, int qos, boolean retained) {
        MqttMessage message = new MqttMessage();
        message.setPayload(pushMessage.getBytes());
        message.setQos(qos);
        message.setRetained(retained);
        MqttTopic mqttTopic = MyMQTTClient.getClient().getTopic(topic);
        if (null == mqttTopic) {
            LOGGER.error("topic is not exist");
        }
        MqttDeliveryToken token;
        synchronized (this) {
            try {
                token = mqttTopic.publish(message);
                token.waitForCompletion(1000L);
            } catch (MqttPersistenceException e) {
                e.printStackTrace();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 订阅某个主题
     *
     * @param topic
     * @param qos
     */
    public void subscribe(String topic, int qos) {
        try {
            MyMQTTClient.getClient().subscribe(topic, qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    /**
     * 取消订阅主题
     *
     * @param topic 主题名称
     */
    public void cleanTopic(String topic) {
        if (client != null && client.isConnected()) {
            try {
                client.unsubscribe(topic);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("取消订阅失败!");
        }
    }
}

MyMqttService.java

package cn.renkai721.mqtt;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 1. @author renkai721@163.com
 2. @date 2023/07/17 16:40
 */
@Service
@EnableAsync
@Slf4j
public class MyMqttService {

	@Autowired
	private MyMQTTClient myMQTTClient;
	@Value("${mqtt.topic1}")
	String topic1;

	private static Map<String,String> longitudeAndLatitudeMap = new ConcurrentHashMap<>();
	static {
		longitudeAndLatitudeMap.put("F23000195","101.80964,3.552734");
		longitudeAndLatitudeMap.put("F23000194","2.364087,48.663712");
		longitudeAndLatitudeMap.put("F23000193","23.171214,-30.008971");
		longitudeAndLatitudeMap.put("F23000192","-59.777335,-22.381016");
		longitudeAndLatitudeMap.put("F23000001","121.49702,31.368703");
		longitudeAndLatitudeMap.put("F23000003","77.311839,13.87632");
		longitudeAndLatitudeMap.put("F23000004","104.022841,30.579637");
		longitudeAndLatitudeMap.put("F23000005","-81.963907,28.519213");
		longitudeAndLatitudeMap.put("F23000008","47.935073,29.28128");
		longitudeAndLatitudeMap.put("F23000010","139.212965,36.169801");
		longitudeAndLatitudeMap.put("F23000308","120.23624,22.92936");
		longitudeAndLatitudeMap.put("F23000307","120.32395,22.61752");
		longitudeAndLatitudeMap.put("F23000306","120.66108,24.17684");
		longitudeAndLatitudeMap.put("F23000305","114.21892,22.28145");
		longitudeAndLatitudeMap.put("F23000304","109.59403,19.50146");
		longitudeAndLatitudeMap.put("F23000303","121.06061,13.20827");
		longitudeAndLatitudeMap.put("F23000302","120.53530,-1.87089");
		longitudeAndLatitudeMap.put("F23000301","110.32614,-7.80236");
		longitudeAndLatitudeMap.put("F23000300","145.24253,-27.52135");
		longitudeAndLatitudeMap.put("F23000299","171.44028,-42.56513");
		longitudeAndLatitudeMap.put("F23000298","-67.43192,-39.55812");
		longitudeAndLatitudeMap.put("F23000297","-69.34524,6.59255");
		longitudeAndLatitudeMap.put("F23000296","24.99610,-13.70725");
		longitudeAndLatitudeMap.put("F23000295","35.00423,40.48366");
		longitudeAndLatitudeMap.put("F23000294","-4.58675,39.57853");
		longitudeAndLatitudeMap.put("F23000293","26.61506,54.09425");
		longitudeAndLatitudeMap.put("F23000292","14.84079,63.88942");
		longitudeAndLatitudeMap.put("F23000291","25.79382,68.38100");
		longitudeAndLatitudeMap.put("F23000290","101.88504,48.52852");
		longitudeAndLatitudeMap.put("F23000289","140.88731,39.30062");
		longitudeAndLatitudeMap.put("F23000288","104.09272,63.46892");
		longitudeAndLatitudeMap.put("F23000287","-154.23031,64.15251");
		longitudeAndLatitudeMap.put("F23000286","-135.03542,64.83030");
		longitudeAndLatitudeMap.put("F23000285","-107.31865,56.20248");
		longitudeAndLatitudeMap.put("F23000284","-105.49845,36.93292");
		longitudeAndLatitudeMap.put("F23000283","-101.11341,25.21778");
		longitudeAndLatitudeMap.put("F23000282","-76.95431,20.93201");
		longitudeAndLatitudeMap.put("F23000281","-52.92645,-9.07194");
		longitudeAndLatitudeMap.put("F23000280","-66.51627,-39.98271");
		longitudeAndLatitudeMap.put("F23000279","24.59100,-30.56490");
		longitudeAndLatitudeMap.put("F23000278","46.50112,-20.91024");
		longitudeAndLatitudeMap.put("F23000277","45.70816,22.30069");
		longitudeAndLatitudeMap.put("F23000276","2.16526,48.04232");
		longitudeAndLatitudeMap.put("F23000275","-18.35814,65.29671");
		longitudeAndLatitudeMap.put("F23000274","-111.55389,67.25068");
		longitudeAndLatitudeMap.put("F23000273","-145.80579,67.71462");
		longitudeAndLatitudeMap.put("F23000272","-75.49705,-10.04124");
		longitudeAndLatitudeMap.put("F23000271","-46.14453,-8.69899");
		longitudeAndLatitudeMap.put("F23000270","-64.17184,8.13274");
		longitudeAndLatitudeMap.put("F23000269","-71.33817,19.00195");
		longitudeAndLatitudeMap.put("F23000268","-70.92216,50.46753");
		longitudeAndLatitudeMap.put("F23000267","-112.52365,64.33525");
		longitudeAndLatitudeMap.put("F23000266","-131.10565,64.87117");
		longitudeAndLatitudeMap.put("F23000265","-156.62124,67.81950");
		longitudeAndLatitudeMap.put("F23000264","-77.36511,41.03387");
		longitudeAndLatitudeMap.put("F23000263","-63.33919,51.62100");
		longitudeAndLatitudeMap.put("F23000262","-74.58598,58.31921");
		longitudeAndLatitudeMap.put("F23000261","170.80659,-44.61839");
		longitudeAndLatitudeMap.put("F23000260","172.42555,-41.82046");
		longitudeAndLatitudeMap.put("F23000259","162.41742,-9.23632");
		longitudeAndLatitudeMap.put("F23000258","132.39303,-27.54709");
		longitudeAndLatitudeMap.put("F23000257","119.73569,-1.86773");
		longitudeAndLatitudeMap.put("F23000256","162.85895,-9.38253");
		longitudeAndLatitudeMap.put("F23000255","46.73522,-20.52389");
		longitudeAndLatitudeMap.put("F23000254","23.48103,-30.90318");
		longitudeAndLatitudeMap.put("F23000253","38.64040,1.39179");
		longitudeAndLatitudeMap.put("F23000252","7.74615,61.69806");
		longitudeAndLatitudeMap.put("F23000251","17.01839,63.78956");
		longitudeAndLatitudeMap.put("F23000250","6.71590,61.06262");
		longitudeAndLatitudeMap.put("F23000249","91.16632,29.61968");
		longitudeAndLatitudeMap.put("F23000248","77.14594,28.75387");
		longitudeAndLatitudeMap.put("F23000247","102.79804,24.84042");
		longitudeAndLatitudeMap.put("F23000246","106.66662,26.62768");
		longitudeAndLatitudeMap.put("F23000245","108.38023,22.83429");
		longitudeAndLatitudeMap.put("F23000244","102.51244,18.98029");
		longitudeAndLatitudeMap.put("F23000243","110.32750,19.79340");
		longitudeAndLatitudeMap.put("F23000242","113.49507,22.18291");
		longitudeAndLatitudeMap.put("F23000241","113.36525,23.21881");
		longitudeAndLatitudeMap.put("F23000240","106.66662,26.62768");
		longitudeAndLatitudeMap.put("F23000239","106.61470,29.57430");
		longitudeAndLatitudeMap.put("F23000238","104.12218,30.61289");
		longitudeAndLatitudeMap.put("F23000237","108.95143,34.39607");
		longitudeAndLatitudeMap.put("F23000236","112.94983,28.20326");
		longitudeAndLatitudeMap.put("F23000235","114.25002,30.54549");
		longitudeAndLatitudeMap.put("F23000234","115.85977,28.63940");
		longitudeAndLatitudeMap.put("F23000233","119.23505,26.06623");
		longitudeAndLatitudeMap.put("F23000232","120.16974,30.18524");
		longitudeAndLatitudeMap.put("F23000231","121.20828,31.08334");
		longitudeAndLatitudeMap.put("F23000230","118.81963,32.12774");
		longitudeAndLatitudeMap.put("F23000229","113.62690,34.78259");
		longitudeAndLatitudeMap.put("F23000228","117.15795,36.62495");
		longitudeAndLatitudeMap.put("F23000227","114.50966,38.03479");
		longitudeAndLatitudeMap.put("F23000226","112.48449,37.84973");
		longitudeAndLatitudeMap.put("F23000225","106.35707,38.46477");
		longitudeAndLatitudeMap.put("F23000224","103.89052,35.97340");
		longitudeAndLatitudeMap.put("F23000223","101.78747,36.62495");
		longitudeAndLatitudeMap.put("F23000222","111.80944,40.85259");
		longitudeAndLatitudeMap.put("F23000221","116.45694,39.91944");
		longitudeAndLatitudeMap.put("F23000220","117.26181,38.91248");
		longitudeAndLatitudeMap.put("F23000219","123.46712,41.67541");
		longitudeAndLatitudeMap.put("F23000218","125.36247,43.83718");
		longitudeAndLatitudeMap.put("F23000217","126.55680,45.81742");
		longitudeAndLatitudeMap.put("F23000216","128.89353,40.46079");
		longitudeAndLatitudeMap.put("F23000215","125.67403,39.66278");
		longitudeAndLatitudeMap.put("F23000214","126.99818,37.54410");
		longitudeAndLatitudeMap.put("F23000213","127.80305,35.76601");
		longitudeAndLatitudeMap.put("F23000212","130.84080,32.04344");
		longitudeAndLatitudeMap.put("F23000211","132.58037,34.59356");
		longitudeAndLatitudeMap.put("F23000210","138.21448,36.67069");
		longitudeAndLatitudeMap.put("F23000209","142.86401,43.20051");
		longitudeAndLatitudeMap.put("F23000208","19.86489,48.70907");
		longitudeAndLatitudeMap.put("F23000207","24.66590,55.06168");
		longitudeAndLatitudeMap.put("F23000206","9.16551,56.52972");
		longitudeAndLatitudeMap.put("F23000205","8.06814,46.95432");
		longitudeAndLatitudeMap.put("F23000204","43.86993,58.44976");
		longitudeAndLatitudeMap.put("F23000203","64.44567,55.60901");
		longitudeAndLatitudeMap.put("F23000202","3.39487,9.48019");
		longitudeAndLatitudeMap.put("F23000201","-69.16891,-24.86286");
		longitudeAndLatitudeMap.put("F23000200","-76.85052,-1.52400");
		longitudeAndLatitudeMap.put("F23000199","-71.22648,-49.64933");
		longitudeAndLatitudeMap.put("F23000198","-111.26497,29.81043");
		longitudeAndLatitudeMap.put("F23000197","-51.43862,64.14108");
		longitudeAndLatitudeMap.put("F23000196","-132.21363,63.47784");
		longitudeAndLatitudeMap.put("F23000195","-96.15024,56.17903");
	}

	@Async
	public void sendMsg() {

		while (true){
			try {
//				long id = 1675673147956924417l;
				long dev_id = 23000009l;
				long time = System.currentTimeMillis()/1000;

				for(Map.Entry<String,String> obj: longitudeAndLatitudeMap.entrySet()){
//					id = id-1;
					dev_id = dev_id+1;
//					String devId = "F"+dev_id;
					String devId = obj.getKey();
					int curOpening = (int)(Math.random()*1000+1);
					Map map = new HashMap<>();
					map.put("devId",devId);
					map.put("type","devdata");
					map.put("time",time);
					map.put("msgid",time);
					Map dataMap = new HashMap<>();
					dataMap.put("workStat",1);
					dataMap.put("workDelta",1);
					dataMap.put("curState",4);
					dataMap.put("enableStat",1);
					dataMap.put("overTemperature",0);
					dataMap.put("generalFault",0);
					dataMap.put("ovTorFault",0);
					dataMap.put("stValFault",0);
					dataMap.put("opnValOvTor",0);
					dataMap.put("clsValOvTor",0);
					dataMap.put("phOutFault",0);
					dataMap.put("curMoForce",0);
					dataMap.put("generalFault",0);
					dataMap.put("curOpening",curOpening);
					dataMap.put("anlgFeedback",0);
					dataMap.put("ctlPara",0);
					dataMap.put("prodId","F101MO230616000103030003");
					dataMap.put("prodModel","EMD20-72-1-eS1-T3WCG4-X");
					dataMap.put("proDate","20230616");
					dataMap.put("ratedMoment",170);
					dataMap.put("netsignal",5);
					dataMap.put("wifiSignal",0);
					dataMap.put("btStatus",0);
					dataMap.put("firmwareVer","1.0.6");
					dataMap.put("devId",devId);
					map.put("data",dataMap);
					JSONObject json = JSONObject.fromObject(map);
					String sendMsg = json.toString();
					myMQTTClient.publish(sendMsg, topic1);
				}
// 5秒钟发送一次
				Thread.sleep(1000*5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

SpringUtils.java

package cn.renkai721.mqtt;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring工具类 方便在非spring管理环境中获取bean
 *
 * @author renkai721@163.com
 */
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware
{
    /** Spring应用上下文环境 */
    private static ConfigurableListableBeanFactory beanFactory;

    private static ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
    {
        SpringUtils.beanFactory = beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 获取对象
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException
    {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     *
     *
     */
    public static <T> T getBean(Class<T> clz) throws BeansException
    {
        T result = (T) beanFactory.getBean(clz);
        return result;
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     */
    public static boolean containsBean(String name)
    {
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     *
     *
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.isSingleton(name);
    }

    /**
     * @param name
     *
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     *
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
    {
        return beanFactory.getAliases(name);
    }

    /**
     * 获取aop代理对象
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker)
    {
        return (T) AopContext.currentProxy();
    }

    /**
     * 获取当前的环境配置,无配置返回null
     */
    public static String[] getActiveProfiles()
    {
        return applicationContext.getEnvironment().getActiveProfiles();
    }

    /**
     * 获取当前的环境配置,当有多个环境配置时,只获取第一个
     */
    public static String getActiveProfile()
    {
        final String[] activeProfiles = getActiveProfiles();
        return activeProfiles.length > 0 ? activeProfiles[0] : null;
    }
}

发送消息

程序启动后,默认只能连接MQTT,然后接收消息。发送消息是通过接口来触发的,所以我们需要手动调用一下接口。接口触发后在控制台就可以看见发送的日志和接收到的日志了。当然直接通过MQTTX客户端订阅消息,也可以看到发送的消息。

控制台日志

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/767989.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

0132 数据的表示和运算1

目录 2.数据的表示和运算 2.1数制与编码 2.1部分习题 2.数据的表示和运算 2.1数制与编码 2.1部分习题 1.若定点整数为64位&#xff0c;含1位符号位&#xff0c;则采用补码表示的最大值最大的负数为&#xff08;&#xff09; A. B. C. D. 2.若x的补…

戴佩妮《随风所遇》世界巡回演唱会内地首站八月启动,乘风归来,相遇之约!

今日&#xff0c;戴佩妮(Penny)《随风所遇2023 Drift World Tour》世界巡回演唱会正式官宣内地首站&#xff0c;8月26日登陆南京太阳宫剧场。自2016年《贼》世界巡回演唱会之后&#xff0c;华语乐坛唱作人戴佩妮乘著所有粉丝期待的“风”回来&#xff0c;并带来曲目、造型等方面…

如何理解操作系统?(Operator System)

文章目录 一.什么是操作系统二.操作系统的层状结构三.操作系统如何管理 一.什么是操作系统 先入为主&#xff0c;操作系统是一款管理软件 操作系统分为两部分 操作系统本身&#xff0c;主要做一些进程管理、内存管理、文件管理、驱动管理等工作&#xff0c;这种核心部分叫做…

归并排序递归与非递归

基本思想 归并排序&#xff08;MERGE-SORT&#xff09;是建立在归并操作上的一种有效的排序算法,该算法是采用分治法&#xff08;Divide andConquer&#xff09;的一个非常典型的应用。将已有序的子序列合并&#xff0c;得到完全有序的序列&#xff1b;即先使每个子序列有序&a…

Jenkins (二)

Jenkins (二) 使用pipeline script 简单编译 发布war工程到远程tomcat中 配置所需 下载 apache-maven-3.9.3.tar.gz 解压 apache-maven-3.9.3-bin.tar.gz 拷贝到 docker jenkins 镜像里 $ docker cp apache-maven-3.9.3 37259c708ca1:/home/下载apache-tomcat-8.5.91.tar.gz …

压测工具之JMeter使用

文章目录 前言压测工具如何使用启动JMeter工具开始创建测试环境1、创建线程组2、配置元件3、构造HTTP请求4、添加HTTP请求头信息 5、添加断言6、添加查看结果树7、添加聚合报告信息8、测试计划创建完成了 执行测试计划 前言 最近公司项目需要进行压测&#xff0c;查验S A A S …

7.18训练总结

考场错误&#xff1a; 今天是一套neerc的题&#xff0c;难度相对较大&#xff0c;我犯的低级错误比较少&#xff0c;但是对于题目顺序的把握能力&#xff0c;应该提高&#xff0c;尝试去做自己擅长的题目&#xff0c;而不是跟着别人的开题顺序&#xff0c;这样能够更顺畅吧。 …

实验室LIMS系统检测工作流程

LIMS系统检测工作流程 检测工作流程是LIMS核心内容&#xff0c;通过检测工作管理可加强协同工作能力、进一步强化质量控制环节、提高数据报出速度&#xff0c;提高工作效率、减低数据出错率&#xff0c;保证质量记录的完整、监控规范的执行&#xff1b;检测流程以样品检测为主…

Jenkins | 获取凭证密码

目录 方法一&#xff1a;查看所有账号及密码 方法二&#xff1a;查看指定账号密码 方法一&#xff1a;查看所有账号及密码 Jenkins > 系统管理 > 脚本命令行 com.cloudbees.plugins.credentials.SystemCredentialsProvider.getInstance().getCredentials().forEach{i…

element-ui message消息提示组件 ①延长提示消息在页面停留时间②提示消息换行

以实现下面的效果为示例 完整代码&#xff1a; let msgList ["数据1被引用", "数据2被引用"];// 使用html的换行标签拼接信息&#xff0c;默认行距太小&#xff0c;此处用两个<br/><br/>let message 以下数据不能删除&#xff0c;原因是&…

【Spring core学习四】Bean作用域和生命周期

目录 一、Bean的作用域 &#x1f308;1、被修改的Bean值现象 &#x1f308;2、 Bean 的 6 种作⽤域 &#x1f308;3、设置作用域 二、Spring的执行流程 三、Bean的生命周期 &#x1f308;1、Bean生命周期的过程 &#x1f308;2、演示生命周期 一、Bean的作用域 &…

[MySql]JDBC编程

JDBC&#xff0c;即Java Database Connectivity&#xff0c;java数据库连接。是一种用于执行SQL语句的Java API&#xff0c;它是Java中的数据库连接规范。这个API由 java.sql.*,javax.sql.* 包中的一些类和接口组成&#xff0c;它为Java开发人员操作数据库提供了一个标准的API&…

全域Serverless化,华为云引领下一代云计算新范式

近日&#xff0c;华为开发者大会2023&#xff08;Cloud&#xff09;在东莞成功举办&#xff0c;期间“全域Serverless化&#xff0c;引领下一代云计算新范式”专题论坛人气满满。华为云首席产品官方国伟携手业界专家、客户、伙伴&#xff0c;面向广大开发者&#xff0c;分享了在…

Authing 身份云上线数据对象管理(元数据),助力企业构建唯一身份源

在身份管理领域&#xff0c;元数据具有重要的作用和价值。元数据有助于理解数据的结构和意义&#xff0c;提升数据处理效率&#xff1b;促进跨部门、跨组织的数据共享和协作&#xff1b;以及支持数据分析&#xff0c;为业务决策提供支持等。当前&#xff0c;Authing 身份云已经…

在ICC/ICC2/FC中运行Calibre

1. which calibre找到calibre的安装目录 > which calibre > /eda/mentor/ixl_cal_version/bin/calibre 2. 在 /eda/mentor/ixl_cal_version目录下使用find ./* -name "icc_calibre.tcl",找到icc_calibre.tcl 3. 打开icc_calibre.tcl里面有不同工具(ICC2/FC/…

《Linux0.11源码解读》理解(五) head之开启分页

先回顾一下地址长度以及组合的演变&#xff1a;16位cpu意味着其数据总线/寄存器也是16位&#xff0c;但是地址总线&#xff08;寻址能力&#xff09;与此无关&#xff0c;可能是20位。可以参考&#xff1a;cpu的位宽、操作系统的位宽和寻址能力的关系_cpu位宽_brahmsjiang的博客…

C++——map和set(multimap和multiset)

目录 1.关联式容器 2.键值对 3.树形结构的关联式容器 3.1 set 3.1.1 set的介绍 3.1.2 set的使用 3.2 multiset 3.2.1 multiset的介绍 3.2.2 multiset的使用 3.3 map 3.3.1 map的介绍 3.3.2 map的使用 3.4 multimap 3.4.1 multimap的介绍 3.4.2 multimap的使用 …

抖音小店选品攻略:10个技巧助你选择助轻松学会选品技巧

抖音小店是目前非常火爆的电商平台之一&#xff0c;许多商家都希望能在抖音上开设自己的小店。而在开设抖音小店之前&#xff0c;选品是一个非常重要的环节。下面是不若与众总结的一些抖音小店选品技巧&#xff0c;希望能帮助到你。 1. 确定目标受众&#xff1a;在选品之前&…

数据库应用:MySQL高级语句

目录 一、理论 1.常用查询 2.函数 3.进阶查询 二、实验 1.普通查询 2.函数 3.进阶查询 三、问题 1.MySQL || 运算符不生效 四、总结 一、理论 1.常用查询 常用查询包括&#xff1a;增、删、改、查&#xff1b; 对 MySQL 数据库的查询&#xff0c;除了基本的查询外…

(学习笔记-TCP连接断开)建立了连接,但是客户端或服务端出现问题,会怎么样?

客户端突然出现故障 客户端出现故障指的是客户端的主机发生了宕机或者断电的场景。发生这种情况的时候&#xff0c;如果服务端一直不会发送数据给客户端&#xff0c;那么服务端是永远无法感知到客户端宕机这件事的&#xff0c;也就是服务端的TCP连接将一直处于ESTABLISH 状态&…