我想知道有没有办法通过Spring Boot Actuator获得CPU使用率指标?我能够看到/ metrics和/ health端点的其他指标,但没有获得CPU使用率。我想避免编写额外的类来查看CPU使用率。任何的想法?谢谢
遗憾的是,Spring Boot Actuator没有可用的CPU指标。 幸运的是,你可以写自己的。
只需创建一个满足以下条件的测量bean:
GaugeService
,因为它将跟踪一个值。
@Autowired
private GaugeService gaugeService;
@PostConstruct
public void startMeasuring() {
new Thread() {
@Override
public void run() {
gaugeService.submit("process.cpu.load", getProcessCpuLoad());
Thread.sleep(2000); //measure every 2sec.
}
}.start();
}
public static double getProcessCpuLoad() throws Exception {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" });
if (list.isEmpty()) return Double.NaN;
Attribute att = (Attribute)list.get(0);
Double value = (Double)att.getValue();
// usually takes a couple of seconds before we get real values
if (value == -1.0) return Double.NaN;
// returns a percentage value with 1 decimal point precision
return ((int)(value * 1000) / 10.0);
}
您还可以使用此方法提取系统范围的CPU负载。
希望这可以帮助。
Spring Boot 2执行器解决方案(基于@ diginoise的代码来测量CPU负载),注册一个Gauge,其功能是在请求时测量值(无需启动线程或计划定时器):
@Component
public class CpuMetrics {
private final static String METRICS_NAME = "process.cpu.load";
@Autowired
private MeterRegistry meterRegistry;
@PostConstruct
public void init() {
Gauge.builder(METRICS_NAME, this, CpuMetrics::getProcessCpuLoad)
.baseUnit("%")
.description("CPU Load")
.register(meterRegistry);
}
public Double getProcessCpuLoad() {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
AttributeList list = mbs.getAttributes(name, new String[]{"ProcessCpuLoad"});
return Optional.ofNullable(list)
.map(l -> l.isEmpty() ? null : l)
.map(List::iterator)
.map(Iterator::next)
.map(Attribute.class::cast)
.map(Attribute::getValue)
.map(Double.class::cast)
.orElse(null);
} catch (Exception ex) {
return null;
}
}
}
然后,/actuator/metrics/process.cpu.load
将提供CPU指标:
{
"name": "process.cpu.load",
"description": "CPU Load",
"baseUnit": "%",
"measurements": [
{
"statistic": "VALUE",
"value": 0.09767676212004521
}
],
"availableTags": []
}