serverWatches.forEach( sw -> { String serverId = sw.getId(); String ip = sw.getIp(); try { saveSystemMonitor(serverId, ip, time, plmxs_url); } catch (Exception e) { log.error("保存cpu使用率|内存使用率失败:{}", e); } try { saveDiskIoDetail(serverId, ip, time, plmxs_url); } catch (Exception e) { log.error("保存磁盘IO失败:{}", e); } try { saveNetIoReceive(serverId, ip, time, plmxs_url); } catch (Exception e) { log.error("保存网络IO-receive失败:{}", e); } try { saveNetIoTransmit(serverId, ip, time, plmxs_url); } catch (Exception e) { log.error("保存网络IO-transmit失败:{}", e); } } );
时间: 2024-02-10 11:13:18 浏览: 65
可以将每个保存操作都放入一个线程中进行执行,这样可以提高并发处理能力,代码如下所示:
```
serverWatches.parallelStream().forEach(sw -> {
String serverId = sw.getId();
String ip = sw.getIp();
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.execute(() -> {
try {
saveSystemMonitor(serverId, ip, time, plmxs_url);
} catch (Exception e) {
log.error("保存cpu使用率|内存使用率失败:{}", e);
}
});
executor.execute(() -> {
try {
saveDiskIoDetail(serverId, ip, time, plmxs_url);
} catch (Exception e) {
log.error("保存磁盘IO失败:{}", e);
}
});
executor.execute(() -> {
try {
saveNetIoReceive(serverId, ip, time, plmxs_url);
} catch (Exception e) {
log.error("保存网络IO-receive失败:{}", e);
}
});
executor.execute(() -> {
try {
saveNetIoTransmit(serverId, ip, time, plmxs_url);
} catch (Exception e) {
log.error("保存网络IO-transmit失败:{}", e);
}
});
executor.shutdown();
});
```
在上面的代码中,我们使用了 Java 自带的线程池进行多线程处理,其中 `newFixedThreadPool(4)` 表示创建一个固定大小为 4 的线程池,每个保存操作都会被分配到其中一个线程中进行执行。最后,我们需要在代码结束前调用 `executor.shutdown()` 来关闭线程池。
阅读全文