获取服务器的CPU和内存信息

[centos@ip-172-31-1-1 tomcat7]$ cat /proc/cpuinfo
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 79
model name  : Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz
stepping    : 1
microcode   : 0xb00002a
cpu MHz     : 2300.137
cache size  : 46080 KB
physical id : 0
siblings    : 1
core id     : 0
cpu cores   : 1
apicid      : 0
initial apicid  : 0
fpu     : yes
fpu_exception   : yes
cpuid level : 13
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx rdtscp lm constant_tsc rep_good nopl xtopology eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single fsgsbase bmi1 avx2 smep bmi2 erms invpcid xsaveopt
bogomips    : 4600.15
clflush size    : 64
cache_alignment : 64
address sizes   : 46 bits physical, 48 bits virtual
power management:
[centos@ip-172-31-1-1 tomcat7]$ free -m
              total        used        free      shared  buff/cache   available
Mem:           1837         910         256           0         670         747
Swap:             0           0           0

从上面的两个命令,可以看到本机器上可以使用一个CPU核并提供1837MB内存。

可以使用Java的Runtime类和Process类来获取Linux服务器CPU内存使用率。具体实现方法如下: 1. 获取CPU使用率: ```java public static double getCpuUsage() { try { Process process = Runtime.getRuntime().exec("top -b -n1"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); while (line != null) { if (line.startsWith("Cpu(s)")) { String[] cpuInfo = line.split("\\s+"); double idleCpuUsage = Double.parseDouble(cpuInfo[4]); double totalCpuUsage = 100 - idleCpuUsage; return totalCpuUsage; } line = reader.readLine(); } } catch (IOException e) { e.printStackTrace(); } return 0; } ``` 2. 获取内存使用率: ```java public static double getMemoryUsage() { try { Process process = Runtime.getRuntime().exec("free -m"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine(); if (line != null) { String[] memoryInfo = line.split("\\s+"); double totalMemory = Double.parseDouble(memoryInfo[1]); double usedMemory = Double.parseDouble(memoryInfo[2]); double memoryUsage = usedMemory / totalMemory * 100; return memoryUsage; } } catch (IOException e) { e.printStackTrace(); } return 0; } ``` 以上代码通过执行Linux命令获取CPU内存使用率,并返回一个double类型的数值,表示使用率的百分比。需要注意的是,这些命令的输出格式可能会因Linux版本而异,需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值