使用collectors.groupingby按healthstatus枚举对节点列表分组,可得各状态节点集合;支持嵌套收集器统计数量、提取主机名或生成节点摘要,并可用于监控报表输出。

使用 Collectors.groupingBy 按节点健康变量统计系统集群分布,核心是将节点列表按健康状态(如 UP、DOWN、UNKNOWN)分组,并可进一步聚合数量、主机列表或详细信息。
明确节点健康状态字段
确保节点对象(例如 Node)有可访问的健康状态属性,常见形式包括:
-
node.getStatus()→ 返回枚举HealthStatus.UP -
node.isHealthy()→ 返回boolean(需转为分类标签) -
node.getHealthCheckResult()→ 返回字符串如"healthy"、"unhealthy"
推荐统一建模为枚举(如 HealthStatus),便于类型安全和后续扩展。
基础分组:按健康状态归类节点列表
最直接的用法是按健康状态分组,得到各状态对应的节点集合:
Map<healthstatus list>> groupedByStatus = nodes.stream()
.collect(Collectors.groupingBy(Node::getStatus));</healthstatus>
结果示例:
{UP=[node-a, node-b], DOWN=[node-c], UNKNOWN=[node-d]}
增强统计:同时获取数量与节点详情
常需既知每类节点数,又保留节点引用。可用嵌套收集器实现:
Map<healthstatus map long>> summary = nodes.stream()
.collect(Collectors.groupingBy(
Node::getStatus,
Collectors.collectingAndThen(
Collectors.groupingBy(
Node::getHostname,
Collectors.counting()
),
map -> {
// 可选:添加总数、平均响应时间等衍生指标
long total = map.values().stream().mapToLong(Long::longValue).sum();
return Map.of("count", total, "by-host", map);
}
)
));</healthstatus>
更实用的简化方式是分别统计:
- 数量统计:
Collectors.groupingBy(Node::getStatus, Collectors.counting()) - 主机名列表:
Collectors.groupingBy(Node::getStatus, Collectors.mapping(Node::getHostname, Collectors.toList())) - 带指标的节点摘要:
Collectors.groupingBy(Node::getStatus, Collectors.mapping(node -> new NodeSummary(node), Collectors.toList()))
结合下游处理生成监控报表
分组后可快速输出集群健康概览,例如:
groupedByStatus.forEach((status, nodeList) -> {
System.out.printf("%s: %d nodes (%.1f%%)%n",
status,
nodeList.size(),
100.0 * nodeList.size() / nodes.size());
nodeList.stream()
.map(Node::getHostname)
.forEach(h -> System.out.println(" └─ " + h));
});
也可转为 JSON 或集成到 Actuator 端点中,供 Prometheus 抓取或前端展示。










