mqtt队列中必须为json对象,才能使用此类
<!--Mqtt-->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.1.0</version>
</dependency>
监听+入库
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.*;
import static com.datacvg.json.JsonObjectUtils.toMap;
/**
* @Author: 商朝
* @Date: 2021.4.14
* @Function: 测试连接+监听并插入至目标表
*/
@Data
@Slf4j
public class DatasourceCrossClient {
private MqttClient mqttClient;
private Boolean clientIdCouldBeUsed = true;
//监听并插入的方法
public void crossSensationLinkListenAndInsert(String username,String password,String broker,String topic,String clientId,String tableName){
//接入服务器域名
MemoryPersistence persistence = new MemoryPersistence();
try {
mqttClient = new MqttClient(broker,clientId,persistence);
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setMqttVersion(4);
//设置是否自动重连
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
mqttConnectOptions.setKeepAliveInterval(90);
mqttClient.connect(mqttConnectOptions);
mqttClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
System.out.println("连接失败,原因:" + throwable);
clientIdCouldBeUsed = false;
}
/**
*
* @Function:监听并插入至表中
*/
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
JSONObject jsonObject = JSONObject.fromObject(new String(mqttMessage.getPayload(),"UTF-8"));
Map<String,Object> maop = new HashMap<>();
toMap(maop,jsonObject);
//注册驱动,导入jar包
Class.forName("com.mysql.cj.jdbc.Driver");
//获得桥梁
String url = "jdbc:mysql://192.168.2.76:3306/database?characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String user = "root";
String pwd = "root";
Connection con = DriverManager.getConnection(url, user, pwd);
//造车sql语句执行器
Statement sta = con.createStatement();
String sql = "insert into "+tableName+"(";
LinkedList<Object> objects = new LinkedList<>();
Set<Map.Entry<String, Object>> entries = maop.entrySet();
for (Map.Entry<String, Object> entry : entries) {
sql+=entry.getKey()+",";
objects.add(entry.getValue());
}
sql =sql.substring(0, sql.lastIndexOf(","))+" )";
sql+=" value(";
//拼接sql
for (Object object : objects) {
if("".equals(object+"")){
sql+="'"+"此处为空"+"'"+",";
}else if(object instanceof Map){
sql+="'"+object.toString()+"'"+",";
}
else {
sql+="'"+object.toString()+"'"+",";
}
}
sql =sql.substring(0, sql.lastIndexOf(","))+" )";
try{
//执行sql
sta.execute(sql);
}catch (Exception e){
log.error("提供方信息有误");
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//如果是qos 0消息 token.resp是没有回复的
System.out.println("消息发送成功!"
+ ((iMqttDeliveryToken == null || iMqttDeliveryToken.getResponse() == null)? "null" : iMqttDeliveryToken.getResponse().getKey()));
}
});
mqttClient.subscribe(topic);
log.info(System.currentTimeMillis() + "成功连接:---");
}catch (Exception e){
e.printStackTrace();
System.out.println("连接失败");
}
}
/**
*
* @param username
* @param password
* @param broker
* @param clientId
* @Function: 测试连接
*/
public void crossSensationLink(String username,String password,String broker,String clientId){
//接入服务器域名
MemoryPersistence persistence = new MemoryPersistence();
MqttClient mqttClient=null;
MqttConnectOptions mqttConnectOptions =null;
try {
mqttClient = new MqttClient(broker, clientId, persistence);
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setMqttVersion(4);
mqttClient.setTimeToWait(3000);
//设置是否自动重连
mqttConnectOptions.setAutomaticReconnect(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
mqttConnectOptions.setKeepAliveInterval(80);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("url不满足tcp协议");
}
try {
mqttClient.connect(mqttConnectOptions);
Thread.sleep(3000);
}catch (MqttException e){
String str =e.getMessage();
if("无权连接".equals(str)){
throw new RuntimeException("用户名密码错误,无权连接");
}else if("等待来自服务器的响应时超时".equals(str)){
throw new RuntimeException("请检查url是否正确");
}else {
throw new RuntimeException("连接失败");
}
}catch (Exception ignored){
throw new RuntimeException("您的操作有误");
}
if(!clientIdCouldBeUsed){
throw new RuntimeException("ClientId已被占用");
}
}
}