Mqtt消费方数据实时入库 cv即用

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已被占用");
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

商朝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值