mqtt
1:mqtt依赖
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
代码
MqttClient sampleClient = null;
ConfigurableApplicationContext Context= SpringApplication.run(Mqtt1Application.class, args);
RedisController redisController =Context.getBean(RedisController.class);
//Test test=Context.getBean(Test.class);
String topic = "/mqtt/tes0t";
String content = "hello 哈哈";
int qos = 0;
String broker = "tcp://172.20.200.115:1883";
String userName = "Test";
String password = "Test";
String clientId = "pubClient";
// 内存存储
MemoryPersistence persistence = new MemoryPersistence();
try {
// 创建客户端
sampleClient = new MqttClient(broker, clientId, persistence);
// 创建链接参数
MqttConnectOptions connOpts = new MqttConnectOptions();
// 在重新启动和重新连接时记住状态
connOpts.setCleanSession(false);
// 设置连接的用户名
connOpts.setUserName(userName);
connOpts.setPassword(password.toCharArray());
// 设置超时时间 单位为秒
connOpts.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
connOpts.setKeepAliveInterval(50);
connOpts.isAutomaticReconnect();
// 设置回调函数
sampleClient.setCallback(new MqttCallback() {
//检测是否失去连接
public void connectionLost(Throwable cause) {
System.out.println("失去连接了");
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
String str = new String(message.getPayload());//电机的相关信息
// NewsController n=new NewsController();
redisController.redis(str);
//System.out.println("88888888888888888>>"+clientId);
//MyThead my = new MyThead();
//if (topic.indexOf("online") != -1) {
// my.sendNews(str);//历史消息
// my.sendStatusPost(topic);//电机状态
// System.out.println("设备上线啦!" + str);
//
//} else if (topic.indexOf("downline") != -1) {
// my.sendNews(str);//历史消息
// my.sendStatusPost(topic);//电机状态
// //my.run();
// System.out.println("设备下线啦!" + str);
//} else if (topic.indexOf("error") != -1) {
// my.sendNews(str);//历史消息
// my.sendStatusPost(topic);//电机状态
// System.out.println("设备故障!" + str);
//} else {
// my.sendPost(obj);//电机相关数据
//}
}
public void deliveryComplete(IMqttDeliveryToken token) {
System.out.println("deliveryComplete---------" + token.isComplete());
}
});
// 建立连接
sampleClient.connect(connOpts);
//订阅消息
sampleClient.subscribe("/motor/device/#", 0);
创建消息
//MqttMessage message = new MqttMessage(content.getBytes());
设置消息的服务质量
//message.setQos(qos);
发布消息
//sampleClient.publish(topic, message);
// 断开连接
// sampleClient.disconnect();
// 关闭客户端
// sampleClient.close();
} catch (MqttException me) {
System.out.println("reason " + me.getReasonCode());
System.out.println("msg " + me.getMessage());
System.out.println("loc " + me.getLocalizedMessage());
System.out.println("cause " + me.getCause());
System.out.println("excep " + me);
me.printStackTrace();
}
}