MongoTemplate \ MQTTJSON \ JSON \ MAP \ JSONObject \ JsonNode

该博客主要介绍了如何处理MQTTJSON数据并将其存储到MongoDB的过程。通过分解JSON消息,提取关键字段如L1_JS_1、L1_QJ_1和L1_GP_1,创建并存储不同类型的Bo对象到数据库。同时,文章展示了代码优化后的实现,将原始代码拆分为更小的、可重用的方法,提高了代码的可读性和维护性。
摘要由CSDN通过智能技术生成

**

MQTTJSON \ JSON \ MAP \ JSONObject \ (Map) JSON.parse \JsonNode jsonNode.path

**

**

MQTTJSON 数据格式

**

{"payload":"\u0001\u0000]{\"22558866\":{\"S1_ZT\":{\"ext_power_volt\":3.670,\"solar_volt\":0.000,\"sw_version\":\"V1.01.03F\"}}}"}

{"payload":"\u0001\u0000W{\"22558866\":{\"L1_QJ_1\":\"0.544,1.342,88.552,1.44,111.53\",\"L1_JS_1\":\"0.58,-0.29,0.69\"}}"}

{"payload":"\u0002\u0000M{\"TD20206666\": {\"L1_GP_1\": {\"2022-05-31T05:01:15Z\": \"29.10,35.80,-33.50\"}}}"}

**

Controller

**

@PostMapping("/11/22/33/MQTTJson")
@ResponseBody
private String sendMQTTJsonTest2(@RequestBody JSONObject body) throws IOException {
    log.info("----------------MQTTJson:------------ " + body);
    this.saveToMongoDb(body);
    rabbitTemplate.convertAndSend("TopicExchange", "Fire.DeviceMassage", body);
    return "消息发送成功: 200";
}
@Autowired
RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

@Autowired
MongoTemplate mongoTemplate;

@Autowired
ObjectMapper objectMapper;

@Autowired
IChenS1ZtService iChenS1ZtService;

@Autowired
IChenL1GpService iChenL1GpService;

@Autowired
IChenL1JsService iChenL1JsService;

@Autowired
IChenL1QjService iChenL1QjService;

**

分解前(开发思路)

**

  @SneakyThrows
    public void saveToDb(JSONObject msg) {
        chenSksMessageChangeAndSave.saveToDB(msg);

        Date dateTime = new Date();
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        String json = JSON.toJSONString(msg);
        JsonNode jsonNode = objectMapper.readTree(json);
        String str = jsonNode.path("payload").asText();

        Map<String, Object> map2 = new HashMap<>();
        map2.put("createTime", createTime);
        map2.put("inputData", json);

        // 数据剪切 封装
        String key1 = null;
        String jsonstr = null;
        MonitorType monitorType = null;

        // 数据key提取  L1_JS_1 L1_QJ_1   L1_GP_1   S1_ZT
        String code = null;
        String keyL1_JS_1 = null;
        String keyL1_QJ_1 = null;
        String keyL1_GP_1 = null;
        String keyS1_ZT_JS = null;
        String keyS1_ZT_QJ = null;

        ChenL1JsBo chenL1JsBo;
        ChenL1QjBo chenL1QjBo;
        ChenL1GpBo chenL1GpBo;

        //获得第一个点的位置
        int index = str.indexOf("{");
        //根据第二个点的位置,截取 字符串。得到结果 result
        String result = "{" + str.substring(index + 1);

        Map map = (Map) JSON.parse(result);
        log.info("map.keySet():" + map.keySet());
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            code = iterator.next();
            log.info("iterator:" + code);
        }

        Set<String> keySet = map.keySet();
        // 遍历keySet,并输出key的值
        for (String key : keySet) {
            jsonstr = JSON.toJSONString(map.get(key));
            Map map3 = (Map) JSON.parse(jsonstr);
            String keySet2 = map3.keySet().toString();
            log.info("map.keySet():" + keySet2);
            Iterator<String> iterator2 = map3.keySet().iterator();
            while (iterator2.hasNext()) {
                log.info("iterator:" + iterator2.next());
            }
            log.info(key + ":" + jsonstr);
            monitorType = JSON.parseObject(jsonstr, MonitorType.class);
//            key1 = key;
        }
        log.info("monitorType:" + monitorType);

        // {"payload":"\u0001\u0000W{\"22558866\":{\"L1_QJ_1\":\"0.544,1.342,88.552,1.44,111.53\",\"L1_JS_1\":\"0.58,-0.29,0.69\"}}"}
        if (ObjectUtils.isNotEmpty(monitorType.getL1_JS_1()) && ObjectUtils.isNotEmpty(monitorType.getL1_QJ_1())) {
            keyL1_JS_1 = "L1_JS_1_" + code;
            keyL1_QJ_1 = "L1_QJ_1_" + code;
            // 解析 倾角:QJ  加速度:JS
            String L1_JS_1_info = monitorType.getL1_JS_1(); // 加速度
            String L1_QJ_1_info = monitorType.getL1_QJ_1(); // 倾角
            log.info("L1_JS_1(): " + L1_JS_1_info); // L1_JS_1(): 0.58,-0.29,0.69
            log.info("L1_QJ_1(): " + L1_QJ_1_info); // L1_QJ_1(): 0.544,1.342,88.552,1.44,111.53

            String string = L1_JS_1_info + ",";
            String substring = string.substring(0, string.length() - 1);
            log.info(substring);
            String[] split = substring.split(",");//以逗号分割

            chenL1JsBo = new ChenL1JsBo();
            List list1 = Arrays.asList(split);
            chenL1JsBo.setGX(list1.get(0).toString());
            chenL1JsBo.setGY(list1.get(1).toString());
            chenL1JsBo.setGZ(list1.get(2).toString());
            chenL1JsBo.setDeviceSource(keyL1_JS_1);
            chenL1JsBo.setType("L1_JS_1");
            chenL1JsBo.setMsgTime(dateTime);
            chenL1JsBo.setCreateTime(dateTime);
            iChenL1JsService.insertByBo(chenL1JsBo);
            map2.put("messageData", chenL1JsBo);
            map2.put("deviceId", keyL1_JS_1);
            mongoTemplate.insert(map2, "device_message_int");

            String string2 = L1_QJ_1_info + ",";
            String substring2 = string2.substring(0, string2.length() - 1);
            log.info(substring2);
            String[] split2 = substring2.split(",");//以逗号分割

            chenL1QjBo = new ChenL1QjBo();
            List list2 = Arrays.asList(split2);
            chenL1QjBo.setX(list2.get(0).toString());
            chenL1QjBo.setY(list2.get(1).toString());
            chenL1QjBo.setZ(list2.get(2).toString());
            chenL1QjBo.setAngle(list2.get(3).toString());
            chenL1QjBo.setAzi(list2.get(4).toString());
            chenL1QjBo.setDeviceSource(keyL1_QJ_1);
            chenL1QjBo.setType("L1_QJ_1");
            chenL1QjBo.setMsgTime(dateTime);
            chenL1QjBo.setCreateTime(dateTime);
            iChenL1QjService.insertByBo(chenL1QjBo);
            map2.put("messageData", chenL1QjBo);
            map2.put("deviceId", keyL1_QJ_1);
            mongoTemplate.insert(map2, "device_message_int");
        }

        // 地表位移 {"payload":"\u0002\u0000M{\"TD20206666\": {\"L1_GP_1\": {\"2022-05-31T05:01:15Z\": \"29.10,35.80,-33.50\"}}}"}
        if (ObjectUtils.isNotEmpty(monitorType.getL1_GP_1())) {
            keyL1_GP_1 = "L1_GP_1_" + code;
            // 解析 地表位移:GP
            List<Map> L1_GP_1 = monitorType.getL1_GP_1();
            Map map1 = L1_GP_1.get(0);

            Iterator<String> iterator2 = map1.values().iterator();
            String L1_GP_1_info = "29.10,35.80,-33.50";
            while (iterator2.hasNext()) {
                L1_GP_1_info = iterator2.next();
                log.info("L1_GP_1(): " + L1_GP_1_info);// 地表位移:iterator:29.10,35.80,-33.50
            }
            String string = L1_GP_1_info + ",";
            String substring = string.substring(0, string.length() - 1);
            log.info(substring);
            String[] split = substring.split(",");//以逗号分割
            for (String string2 : split) {
                log.info("数据-29.10,35.80,-33.50->>>" + string2);
            }

            chenL1GpBo = new ChenL1GpBo();
            List list = Arrays.asList(split);
            chenL1GpBo.setGpsTotalX(list.get(0).toString());
            chenL1GpBo.setGpsTotalY(list.get(1).toString());
            chenL1GpBo.setGpsTotalZ(list.get(2).toString());
            chenL1GpBo.setDeviceSource(keyL1_GP_1);
            chenL1GpBo.setType("L1_GP_1");
            chenL1GpBo.setMsgTime(dateTime);
            chenL1GpBo.setCreateTime(dateTime);
            iChenL1GpService.insertByBo(chenL1GpBo);
            map2.put("messageData", chenL1GpBo);
            map2.put("deviceId", keyL1_GP_1);
            mongoTemplate.insert(map2, "device_message_int");

        }

        // {"payload":"\u0001\u0000]{\"22558866\":{\"S1_ZT\":{\"ext_power_volt\":3.670,\"solar_volt\":0.000,\"sw_version\":\"V1.01.03F\"}}}"}
        if (ObjectUtils.isNotEmpty(monitorType.getS1_ZT())) {
            keyS1_ZT_JS = "L1_JS_1_" + code;
            keyS1_ZT_QJ = "L1_QJ_1_" + code;
            // 解析 设备状态:ZT
            List<ZT> S1_ZT = monitorType.getS1_ZT(); //设备状态
            log.info("S1_ZT(): " + S1_ZT);
            ZT zt = S1_ZT.get(0);
            ChenS1ZtBo chenS1ZtBo = new ChenS1ZtBo();
            chenS1ZtBo.setBatteryDumpEnergy(zt.getBattery_dump_energy());
            chenS1ZtBo.setExtPowerVolt(zt.getExt_power_volt());
            chenS1ZtBo.setSolarVolt(zt.getSolar_volt());
            chenS1ZtBo.setHumidity("-1");
            chenS1ZtBo.setTemp("-1");
            chenS1ZtBo.setMsgTime(dateTime);
            chenS1ZtBo.setCreateTime(dateTime);

            chenS1ZtBo.setDeviceSource(keyS1_ZT_JS);
            chenS1ZtBo.setType("L1_JS_1");
            iChenS1ZtService.insertByBo(chenS1ZtBo);
            map2.put("messageData", chenS1ZtBo);
            map2.put("deviceId", keyS1_ZT_JS);
            mongoTemplate.insert(map2, "device_message_int");

            chenS1ZtBo.setDeviceSource(keyS1_ZT_QJ);
            chenS1ZtBo.setType("L1_QJ_1");
            iChenS1ZtService.insertByBo(chenS1ZtBo);
            map2.put("messageData", chenS1ZtBo);
            map2.put("deviceId", keyS1_ZT_QJ);
            mongoTemplate.insert(map2, "device_message_int");
        }

        log.info(keyL1_JS_1 + keyL1_QJ_1 + keyL1_GP_1 + keyS1_ZT_JS + keyS1_ZT_QJ);

    }

**

分解后(优化)

**


    @SneakyThrows
    public void saveToDB(JSONObject msg) {
        String json = JSON.toJSONString(msg);
        Map map = this.changeJson(json);
        String code = this.getCdoe(map);
        MonitorType monitorType = this.changeToMonitorType(map);
        if (ObjectUtils.isNotEmpty(monitorType.getL1_JS_1()) && ObjectUtils.isNotEmpty(monitorType.getL1_QJ_1())) {
            this.Save_Li_JS_QJ(monitorType, code, json);
        }
        if (ObjectUtils.isNotEmpty(monitorType.getL1_GP_1())) {
            this.Save_L1_GP(monitorType, code, json);
        }
        if (ObjectUtils.isNotEmpty(monitorType.getS1_ZT())) {
            this.Save_S1_ZT(monitorType, code, json);
        }
    }

    @SneakyThrows
    private Map changeJson(String json) {
        JsonNode jsonNode = objectMapper.readTree(json);
        String str = jsonNode.path("payload").asText();
        int index = str.indexOf("{");
        String result = "{" + str.substring(index + 1);
        Map map = (Map) JSON.parse(result);
        return map;
    }

    private String getCdoe(Map map) {
        String code = null;
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            code = iterator.next();
        }
        return code;
    }

    private MonitorType changeToMonitorType(Map map) {
        MonitorType monitorType = null;
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            String jsonstr = JSON.toJSONString(map.get(key));
            monitorType = JSON.parseObject(jsonstr, MonitorType.class);
        }
        return monitorType;
    }

    private void Save_Li_JS_QJ(MonitorType monitorType, String code, String json) {
        // {"payload":"\u0001\u0000W{\"22558866\":{\"L1_QJ_1\":\"0.544,1.342,88.552,1.44,111.53\",\"L1_JS_1\":\"0.58,-0.29,0.69\"}}"}
        if (ObjectUtils.isNotEmpty(monitorType.getL1_JS_1()) && ObjectUtils.isNotEmpty(monitorType.getL1_QJ_1())) {
            ChenL1JsBo chenL1JsBo = this.setChenL1JsBo(monitorType, code);
            iChenL1JsService.insertByBo(chenL1JsBo);
            this.MGInsert(json, chenL1JsBo, "L1_JS_1", code);

            ChenL1QjBo chenL1QjBo = setChenL1QjBo(monitorType, code);
            iChenL1QjService.insertByBo(chenL1QjBo);
            this.MGInsert(json, chenL1QjBo, "L1_QJ_1", code);
        }
    }

    // 地表位移 {"payload":"\u0002\u0000M{\"TD20206666\": {\"L1_GP_1\": {\"2022-05-31T05:01:15Z\": \"29.10,35.80,-33.50\"}}}"}
    private void Save_L1_GP(MonitorType monitorType, String code, String json) {
        ChenL1GpBo chenL1GpBo = this.setChenL1GpBo(monitorType, code);
        iChenL1GpService.insertByBo(chenL1GpBo);
        this.MGInsert(json, chenL1GpBo, "L1_GP_1", code);
    }

    // {"payload":"\u0001\u0000]{\"22558866\":{\"S1_ZT\":{\"ext_power_volt\":3.670,\"solar_volt\":0.000,\"sw_version\":\"V1.01.03F\"}}}"}
    private void Save_S1_ZT(MonitorType monitorType, String code, String json) {

        ChenS1ZtBo chenS1ZtBo1 = this.setChenS1ZtBo(monitorType, code, "L1_JS_1");
        iChenS1ZtService.insertByBo(chenS1ZtBo1);
        this.MGInsert(json, chenS1ZtBo1, "L1_JS_1", code);

        ChenS1ZtBo chenS1ZtBo2 = this.setChenS1ZtBo(monitorType, code, "L1_QJ_1");
        iChenS1ZtService.insertByBo(chenS1ZtBo2);
        this.MGInsert(json, chenS1ZtBo2, "L1_QJ_1", code);
    }

    private void MGInsert(String json, Object object, String type, String code) {
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("createTime", createTime);
        map.put("inputData", json);
        map.put("messageData", object);
        map.put("deviceId", type + "_" + code);
        mongoTemplate.insert(map, "device_message_int");
    }

    private ChenL1JsBo setChenL1JsBo(MonitorType monitorType, String code) {
        Date dateTime = new Date();
        String L1_JS_1_info = monitorType.getL1_JS_1();
        String string = L1_JS_1_info + ",";
        String substring = string.substring(0, string.length() - 1);
        String[] split = substring.split(",");
        List list1 = Arrays.asList(split);
        ChenL1JsBo chenL1JsBo = new ChenL1JsBo();
        chenL1JsBo.setGX(list1.get(0).toString());
        chenL1JsBo.setGY(list1.get(1).toString());
        chenL1JsBo.setGZ(list1.get(2).toString());
        chenL1JsBo.setDeviceSource("L1_JS_1_" + code);
        chenL1JsBo.setType("L1_JS_1");
        chenL1JsBo.setMsgTime(dateTime);
        chenL1JsBo.setCreateTime(dateTime);
        return chenL1JsBo;
    }

    private ChenL1QjBo setChenL1QjBo(MonitorType monitorType, String code) {
        Date dateTime = new Date();
        String L1_QJ_1_info = monitorType.getL1_QJ_1();
        String string2 = L1_QJ_1_info + ",";
        String substring2 = string2.substring(0, string2.length() - 1);
        String[] split2 = substring2.split(",");//以逗号分割
        List list2 = Arrays.asList(split2);
        ChenL1QjBo chenL1QjBo = new ChenL1QjBo();
        chenL1QjBo.setX(list2.get(0).toString());
        chenL1QjBo.setY(list2.get(1).toString());
        chenL1QjBo.setZ(list2.get(2).toString());
        chenL1QjBo.setAngle(list2.get(3).toString());
        chenL1QjBo.setAzi(list2.get(4).toString());
        chenL1QjBo.setDeviceSource("L1_QJ_1_" + code);
        chenL1QjBo.setType("L1_QJ_1");
        chenL1QjBo.setMsgTime(dateTime);
        chenL1QjBo.setCreateTime(dateTime);
        return chenL1QjBo;
    }

    private ChenL1GpBo setChenL1GpBo(MonitorType monitorType, String code) {
        Date dateTime = new Date();
        List<Map> L1_GP_1 = monitorType.getL1_GP_1();
        Map map1 = L1_GP_1.get(0);
        Iterator<String> iterator2 = map1.values().iterator();
        String L1_GP_1_info = "29.10,35.80,-33.50";
        while (iterator2.hasNext()) {
            L1_GP_1_info = iterator2.next();
        }
        String string = L1_GP_1_info + ",";
        String substring = string.substring(0, string.length() - 1);
        String[] split = substring.split(",");//以逗号分割
        List list = Arrays.asList(split);
        ChenL1GpBo chenL1GpBo = new ChenL1GpBo();
        chenL1GpBo.setGpsTotalX(list.get(0).toString());
        chenL1GpBo.setGpsTotalY(list.get(1).toString());
        chenL1GpBo.setGpsTotalZ(list.get(2).toString());
        chenL1GpBo.setDeviceSource("L1_GP_1_" + code);
        chenL1GpBo.setType("L1_GP_1");
        chenL1GpBo.setMsgTime(dateTime);
        chenL1GpBo.setCreateTime(dateTime);

        return chenL1GpBo;
    }

    private ChenS1ZtBo setChenS1ZtBo(MonitorType monitorType, String code, String type) {
        Date dateTime = new Date();
        List<ZT> S1_ZT = monitorType.getS1_ZT(); //设备状态
        ZT zt = S1_ZT.get(0);
        ChenS1ZtBo chenS1ZtBo = new ChenS1ZtBo();
        chenS1ZtBo.setBatteryDumpEnergy(zt.getBattery_dump_energy());
        chenS1ZtBo.setExtPowerVolt(zt.getExt_power_volt());
        chenS1ZtBo.setSolarVolt(zt.getSolar_volt());
        chenS1ZtBo.setHumidity("-1");
        chenS1ZtBo.setTemp("-1");
        chenS1ZtBo.setMsgTime(dateTime);
        chenS1ZtBo.setCreateTime(dateTime);
        String keyS1_ZT_JS = type + "_" + code;
        chenS1ZtBo.setDeviceSource(keyS1_ZT_JS);
        chenS1ZtBo.setType(type);
        return chenS1ZtBo;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值