CountDownLatch的实际中的使用

发布时间 2023-03-25 17:51:47作者: 曹军

  接口太慢,其中一种方式就是使用多线程进行快速处理。

  介绍下,如何在项目中写代码的。

 

  这里在for循环里使用调用,不是好方式,碍于接口只支持单个节点的查询。

    private List<DeviceInfo> getDeviceByEmissionNoList(Long customerId, List<String> emissionSourceNoList) {
        List<DeviceInfo> deviceNoList = Lists.newArrayList();
        CountDownLatch countDownLatch = new CountDownLatch(emissionSourceNoList.size());
        for (String emissionSourceNo : emissionSourceNoList) {
            executor.submit(() -> {
                try {
                    NodeInfo<Object, Object> nodeInfo = emissionSourceServiceFeign.queryDownVertex(DtoConvert.buildEmissionSourceVertexInfo(customerId, emissionSourceNo));
                    if (Objects.nonNull(nodeInfo)) {
                        List<VertexInfo<Object>> nodes = nodeInfo.getNodes();
                        if (!CollectionUtils.isEmpty(nodes)) {
                            nodes.forEach(node -> {
                                if (Objects.equals(VertexLabelConstants.MONITOR, node.getLabel()) || Objects.equals(VertexLabelConstants.GOVERN, node.getLabel())) {
                                    LinkedHashMap deviceInfoMap = (LinkedHashMap) node.getNode();
                                    if (Objects.nonNull(deviceInfoMap)) {
                                        DeviceInfo deviceInfo = (DeviceInfo) MetaClassUtil.mapToObj(deviceInfoMap, DeviceInfo.class);
                                        deviceInfo.setLabel(node.getLabel());
                                        deviceNoList.add(deviceInfo);
                                    }
                                }

                            });
                        }
                    }
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deviceNoList;
    }

  注意点:

  1.await放在外面

  2.构造函数的size个数

  3.countDown的时候,需要放在finally中

 

二:接口慢查

  针对上面的这段查询,一般可以考虑三个方面的处理:

  1.直接批量处理

  2.多线程处理

  3.查询完成后,使用缓存,但是需要看看是否是常变化的数据,缓存效果并不大。