mqtt java客户端(eclipse paho)简单使用、调试记录

简单使用

v3客户端

 Map<String,Integer> topics = new HashMap<String,Integer>();

        MqttClient mqttClient = new MqttClient("tcp://192.168.0.2:1883",MqttClient.generateClientId());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);
        //该类型是重连重新订阅的必要类,使用普通Callback没有connectComplete方法
        mqttClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                System.out.println("连接成功");
                if(reconnect){
                    topics.forEach((k,v)->{
                        try {
                            mqttClient.subscribe(k,v);
                        } catch (MqttException e) {
                            System.err.println(e.getMessage());
                            e.printStackTrace();
                        }
                    });
                    System.out.println("重连成功");
                }
            }

            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("连接丢失");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("消息到达"+topic+":"+new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("消息投递成功");
            }
        });
        mqttClient.connect(options);

        topics.put("test/003",1);
        mqttClient.subscribe("test/003",1);

v5客户端


        Map<String,Integer> topicsMap = new HashMap<>();

        String serverURI = "tcp://192.168.0.2:1883";
        String clientId = UUID.randomUUID().toString();

        MqttClient client = new MqttClient(serverURI, clientId, new MemoryPersistence());
        MqttConnectionOptions options = new MqttConnectionOptionsBuilder()
                //自动重连,由于paho机制,需要在重连回调中重新订阅之前的topic
                .automaticReconnect(true)
                //遗嘱消息
//                .will("/will",new MqttMessage(client.getClientId().getBytes()))
                .connectionTimeout(10)
                .cleanStart(false)
                .keepAliveInterval(20)
                .build();

        client.connect(options);
        //回调处理
        client.setCallback(new MqttCallback() {

            /**
             * 断连回调
             */
            @Override
            public void disconnected(MqttDisconnectResponse disconnectResponse) {
                System.out.println("Disconnected");
            }

            /**
             * 异常发生回调
             */
            @Override
            public void mqttErrorOccurred(MqttException exception) {
                System.out.println("mqttErrorOccurred");
            }

            /**
             * 接收消息回调
             */
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("messageArrived");
            }

            /**
             * 发送消息回调
             */
            @Override
            public void deliveryComplete(IMqttToken token) {
                System.out.println("deliveryComplete");
            }

            /**
             * 连接完成时回调
             */
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                // 连接完成时,重新订阅所有缓存的Topic
                if (reconnect) {
                    topicsMap.forEach((topic, qos) -> {
                        try {
                            client.subscribe(topic, qos);
                            System.out.println("Resubscribed to topic: " + topic + " with QoS: " + qos);
                        } catch (MqttException e) {
                            System.err.println("Failed to resubscribe to topic: " + topic);
                            e.printStackTrace();
                        }
                    });
                }

                System.out.println("Connected to " + serverURI);
            }


            @Override
            public void authPacketArrived(int reasonCode, MqttProperties properties) {
                System.out.println("authPacketArrived");
            }

        });


        topicsMap.put("test/001", 1);
        topicsMap.put("test/002", 2);

        client.subscribe(new MqttSubscription[]{new MqttSubscription("test/001")});
        client.subscribe("test/002",2);

调试

在依赖中找到jsr47min.properties文件,将该文件复制到项目下,使用-Djava.util.logging.config.file=/xxx(绝对值路径)启动
img

修改日志级别以及将日志输出到console中:

# Properties file which configures the operation of the JDK logging facility.
#
# The configuration in this file is the suggesgted configuration
# for collecting trace for helping debug problems related to the
# Paho MQTT client.  It configures trace to be continuosly collected
# in memory with minimal impact on performance. 
# 
# When the push trigger (by default a Severe level message) or a 
# specific request is made to "push" the in memory trace then it 
# is "pushed" to the configured target handler. By default
# this is the standard java.util.logging.FileHandler. The Paho Debug 
# class can be used to push the memory trace to its target 
# 
# To enable trace either:
# - use this properties file as is and set the logging facility up 
#   to use it by configuring the util logging system property e.g.
#
# >java -Djava.util.logging.config.file=<location>\jsr47min.properties
#
# - This contents of this file can also be merged with another
#   java.util.logging config file to ensure provide wider logging 
#   and trace including Paho trace 

# Global logging properties.
# ------------------------------------------
# The set of handlers to be loaded upon startup.
# Comma-separated list of class names.
# - Root handlers are not enabled by default - just handlers on the Paho packages. 
#handlers=java.util.logging.MemoryHandler,java.util.logging.FileHandler, java.util.logging.ConsoleHandler

# Default global logging level.
# Loggers and Handlers may override this level

# 设置日志级别 所有消息都打印
.level=ALL

# Loggers
# ------------------------------------------
# A memoryhandler is attached to the paho packages
# and the level specified to collected all trace related
# to paho packages.  This will override any root/global
# level handlers if set.

org.eclipse.paho.mqttv5.client.handlers=java.util.logging.MemoryHandler
org.eclipse.paho.mqttv5.client.level=ALL

# It is possible to set more granular trace on a per class basis e.g.
#org.eclipse.paho.mqttv5.client.internal.ClientComms.level=ALL

# Handlers
# -----------------------------------------
# Note: the target handler that is associated with the MemoryHandler is not a root handler 
# and hence not returned when getting the handlers from root. It appears accessing 
# target handler programatically is not possible as target is a private variable in 
# class MemoryHandler
java.util.logging.MemoryHandler.level=ALL
java.util.logging.MemoryHandler.size=10000
java.util.logging.MemoryHandler.push=ALL
#java.util.logging.MemoryHandler.target=java.util.logging.FileHandler
# 设置console输出
java.util.logging.MemoryHandler.target=java.util.logging.ConsoleHandler

#输出到文件
# --- FileHandler ---
# Override of global logging level
#java.util.logging.FileHandler.level=ALL

# Naming style for the output file:
# (The output file is placed in the directory
# defined by the "user.home" System property.)
# See java.util.logging for more options 
#java.util.logging.FileHandler.pattern=%h/ibm/paho/trace/paho%u.log
#java.util.logging.FileHandler.pattern=logs/paho/trace/paho%u.log

# Limiting size of output file in bytes:
#java.util.logging.FileHandler.limit=200000

# Number of output files to cycle through, by appending an
# integer to the base file name:
#java.util.logging.FileHandler.count=3

# Style of output (Simple or XML):
#java.util.logging.FileHandler.formatter=org.eclipse.paho.mqttv5.client.logging.SimpleLogFormatter

# --- ConsoleHandler ---
# Override of global logging level
java.util.logging.ConsoleHandler.level=ALL
#java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
# 日志格式化器
java.util.logging.ConsoleHandler.formatter=org.eclipse.paho.mqttv5.client.logging.SimpleLogFormatter

posted on 2025-03-31 16:49  树下的  阅读(377)  评论(0)    收藏  举报