这段代码使用 computeIfAbsent 方法来存储指标数据,确保不会因为重复的 hostId 导致数据覆盖。

computeIfAbsent 方法会先判断 hostId 是否存在于 metricValueMap 中。如果存在,则返回对应的 List;如果不存在,则创建一个新的 List 并将其与 hostId 关联起来。

因此,即使有多个指标具有相同的 hostId,它们也会被添加到同一个 List 中,而不是覆盖之前的数据。

以下是代码解析:

Map<String, List<MetricItem>> metricValueMap = new HashMap<>();
SugonMetrics.hostMetricMap.entrySet().parallelStream().forEach(entry -> {
    String m8MetricName = entry.getKey();
    String metricName = entry.getValue();
    long time = System.currentTimeMillis();
    String metricPath = sugonConfig.getMetricsValuePath() + "?namespace=" + GlobalConstant.METRIC_HOST_NAMESPACE
            + "&metricName=" + metricName + "&startTime=" + time + "&endTime=" + time;
    JSONObject hostMetric = request(endpoint, metricPath, token);
    if (hostMetric != null) {
        JSONArray hostMetricArray = hostMetric.getJSONArray("data");
        hostMetricArray.forEach(metric -> {
            JSONObject metricJson = (JSONObject) metric;
            String metricValue = metricJson.getString("value");
            String hostId = metricJson.getJSONObject("labels").getString("HostUuid");
            Map<String, String> metricLabels = new HashMap<>();
            metricLabels.put("m8Type", "host");
            MetricItem metricItem = new MetricItem();
            metricItem.setMetricName(m8MetricName);
            metricItem.setMetricValue(metricValue);
            metricItem.setMetricLabels(metricLabels);
            metricValueMap.computeIfAbsent(hostId, k -> new ArrayList<>()).add(metricItem);
        });
    }
});

总结来说,computeIfAbsent 方法可以确保每个 hostId 都对应一个独立的 List,从而避免数据覆盖的问题。

Java 代码解析:使用 computeIfAbsent 方法存储指标数据

原文地址: https://www.cveoy.top/t/topic/obSq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录