引入pom
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>3.5.0</version>
</dependency>
1.创建OS工具类
import lombok.extern.slf4j.Slf4j;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import java.math.RoundingMode;
import java.text.DecimalFormat;
@Slf4j
public class OSUtils {
private static final SystemInfo SI = new SystemInfo();
private static HardwareAbstractionLayer hal = SI.getHardware();
public static final String TWO_DECIMAL = "0.00";
/**
* whether is windows
* @return true if windows
*/
public static boolean isWindows() {
return getOSName().startsWith("Windows");
}
/**
* get current OS name
* @return current OS name
*/
public static String getOSName() {
return System.getProperty("os.name");
}
/**
* get memory usage
* Keep 2 decimal
* @return percent %
*/
public static String memoryUsage() {
GlobalMemory memory = hal.getMemory();
double memoryUsage = (memory.getTotal() - memory.getAvailable() ) * 0.1 / memory.getTotal() * 10*100;
DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
df.setRoundingMode(RoundingMode.HALF_UP);
return df.format(memoryUsage);
}
/**
* load average
*
* @return load average
*/
public static String loadAverage() {
double loadAverage = hal.getProcessor().getSystemLoadAverage(2)[1];
DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
df.setRoundingMode(RoundingMode.HALF_UP);
return df.format(loadAverage);
}
/**
* get cpu usage
*
* @return cpu usage
*/
public static String cpuUsage() {
CentralProcessor processor = hal.getProcessor();
double cpuUsage = processor.getSystemCpuLoad()*100;
DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
Spring Boot结合Redis获取多节点服务器资源信息

最低0.47元/天 解锁文章
2061

被折叠的 条评论
为什么被折叠?



