| package com.doumee.core.mqtt.service; | 
|   | 
| import com.doumee.core.mqtt.config.MqttClientInit; | 
| import com.doumee.core.mqtt.config.MqttConfig; | 
| import org.eclipse.paho.client.mqttv3.MqttMessage; | 
| import org.springframework.beans.factory.annotation.Autowired; | 
| import org.springframework.stereotype.Service; | 
|   | 
| import javax.annotation.PostConstruct; | 
|   | 
| @Service | 
| public class MqttToolService { | 
|     @Autowired | 
|     private MqttConfig config; | 
|     @Autowired | 
|     private MqttPushCallback callBack ; | 
|   | 
|     /** | 
|      * 订阅消息,启动加载一次 | 
|      * @param topics | 
|      */ | 
|     public void subscribe(String[]  topics) { | 
|         try { | 
|             //订阅消息 | 
|             int[] Qos = new int[topics.length];//0:最多一次 、1:最少一次 、2:只有一次 | 
|             for (int i = 0; i < Qos.length; i++) { | 
|                 Qos[i] = 1; | 
|             } | 
|             MqttClientInit.getSubInstance(config,callBack).subscribe(topics, Qos); | 
|         } catch (Exception e) { | 
|             e.printStackTrace(); | 
|         } | 
|     } | 
|     /** | 
|      * 消息发送 | 
|      * @param message | 
|      * @param topic | 
|      */ | 
|     public  int pubMessage(String message,String topic){ | 
|         MqttMessage mess = new MqttMessage(); | 
|         mess.setQos(1); | 
|         mess.setRetained(true); | 
|         mess.setPayload(message.getBytes()); | 
|         try { | 
|             MqttClientInit.getInstance(config).publish(topic, mess); | 
|             return  0; | 
|         } catch (Exception e) { | 
|             //LOGGER.error(e.getLocalizedMessage()); | 
|         } | 
|         return 1; | 
|     } | 
|     public static void main(String[] args) { | 
|         MqttToolService client1 = new MqttToolService(); | 
|         client1.pubMessage("你好啊","test"); | 
|     } | 
|   | 
| } |