jar包
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>
工具类
package com.tw.tongli.common.mqtt;
/**
* Mqtt基础配置信息
* @author
*/
public class MqttConfig {
/** 订阅消息主题 - 可为多个 现指一个作为示例 */
public static final String TOPIC = "test/topic";
/** QOS */
public static final Integer QOS = 2;
/** 链接地址 */
public static final String IP_ADDRESS = "tcp://192.168.1.87:1883"; //服务器地址
/** 用户名 */
public static final String USERNAME = "admin";
/** 密码 */
public static final String PASSWD = "admin";
/*QoS0 代表,Sender 发送的一条消息,Receiver 最多能收到一次,也就是说 Sender 尽力向 Receiver 发送消息,如果发送失败,也就算了;
QoS1 代表,Sender 发送的一条消息,Receiver 至少能收到一次,也就是说 Sender 向 Receiver 发送消息,如果发送失败,会继续重试,直到 Receiver 收到消息为止,但是因为重传的原因,Receiver 有可能会收到重复的消息;
QoS2 代表,Sender 发送的一条消息,Receiver 确保能收到而且只收到一次,也就是说 Sender 尽力向 Receiver 发送消息,如果发送失败,会继续重试,直到 Receiver 收到消息为止,同时保证 Receiver 不会因为消息重传而收到重复的消息。*/
}
package com.tw.tongli.common.mqtt;
import lombok.extern.slf4j.Slf4j;
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;
import org.springframework.stereotype.Component;
/**
* MQTT处理器
* @author
*/
@Component
@Slf4j
public class MqttHandle implements MqttCallback {
/** 日志组件 */
// private static Logger log = LoggerFactory.getLogger(MqttHandle.class);
/**
* 连接丢失
* @param cause
*/
@Override
public void connectionLost(Throwable cause) {
System.out.println("connection lost:" + cause.getMessage());
MqttInitialized.reconnection();
}
/**
* 收到消息
* @param topic
* @param message
*/
@Override
public void messageArrived(String topic, MqttMessage message) {
log.info("订阅消息已收到...");
System.out.println("topic:" + topic);
System.out.println("Qos:" + message.getQos());
System.out.println("message_content:" + new String(message.getPayload()));
// System.out.println("Received message: \n topic:" + topic + "\n Qos:" + message.getQos() + "\n payload:" + new String(message.getPayload()));
}
/**
* 消息传递成功
* @param token
*/
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------" + token.isComplete());
}
}
package com.tw.tongli.common.mqtt;
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.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* 初始化MQTT客户端
* @author
*/
@Component
public class MqttInitialized {
/** MQTT客户端 */
private static MqttClient client = null;
/** 连接选项 */
private static MqttConnectOptions connOpts = null;
/** 连接状态 */
private static Boolean connectStatus = false;
/** 日志组件 */
private static Logger log = LoggerFactory.getLogger(MqttInitialized.class);
/**
* 获取MQTT客户端连接状态
* @return
*/
public static Boolean getConnectStatus() {
return connectStatus;
}
static {
try {
// MQTT 连接选项
connOpts = new MqttConnectOptions();
// 设置认证信息
connOpts.setUserName(MqttConfig.USERNAME);
connOpts.setPassword(MqttConfig.PASSWD.toCharArray());
// 持久化
MemoryPersistence persistence = new MemoryPersistence();
// MQ客户端建立
client = new MqttClient(MqttConfig.IP_ADDRESS, "tw", persistence);
// 设置回调
client.setCallback(new MqttHandle());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* MQTT客户端启动
*/
@PostConstruct
public static void connect() {
try {
// 建立连接
client.connect(connOpts);
connectStatus = client.isConnected();
log.info("MQTT服务器连接成功~~~");
} catch (Exception e) {
connectStatus = client.isConnected();
log.error("MQTT服务器连接失败!!");
e.printStackTrace();
reconnection();
}
}
/**
* 消息订阅
* @param topic 主题
* @param qos QOS
*/
public void subscribe(String topic, Integer qos) throws MqttException {
client.subscribe(topic, qos);
}
/**
* 消息发布
* @param topic 主题
* @param message 消息体
* @param qos QOS
*/
public void publish(String topic, String message, Integer qos) throws MqttException {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
mqttMessage.setQos(qos);
client.publish(topic, mqttMessage);
}
/**
* 断线重连
*/
public static void reconnection() {
// 尝试进行重新连接
while (true) {
if (MqttInitialized.getConnectStatus()) {
// 查询连接状态 连接成功则停止重连
break;
}
try {
log.info("开始进行MQTT服务器连接.......");
// 进行连接
connect();
Thread.sleep(10000);
} catch (Exception e) {
log.error("重新连接出现异常");
e.printStackTrace();
break;
}
}
}
/**
* 测试方法 进行消息订阅
*/
public void test() {
try {
subscribe(MqttConfig.TOPIC, MqttConfig.QOS);
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
}
测试接口:
@RestController
@RequestMapping("a")
@Slf4j
public class MqttController {
@Resource
private MqttInitialized mqttInitialized;
@GetMapping("b")
public void receive(@RequestParam (value = "message") String message) throws MqttException {
mqttInitialized.subscribe("stock",2); //订阅
mqttInitialized.publish("stock",message,2);//发布
// mqttImpl.MqttCallBack();
}
总结
ok