java获取linux服务器内存⼤⼩、cup使⽤率、内存⼤⼩和使⽤
代码参考了很多博客,这⾥就不⼀⼀贴出原链接了,感谢!
返回⼤⼩单位是M,返回的数据也不是百分⽐的这种,后期可以⾃⾏优化。
1.获取cpu使⽤率:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.log4j.Logger;
/
**
* 采集CPU使⽤率
*/
public class CpuUsage {
private static Logger log = Logger(CpuUsage.class);
private static CpuUsage INSTANCE = new CpuUsage();
private CpuUsage(){
}
public static CpuUsage getInstance(){
return INSTANCE;
}
/
**
* Purpose:采集CPU使⽤率
* @param args
* @return float,CPU使⽤率,⼩于1
*/
public static float getCpuUsage() {
log.info("开始收集cpu使⽤率");
float cpuUsage = 0;
Process pro1,pro2;
Runtime r = Runtime();
try {
String command = "cat /proc/stat";
//第⼀次采集CPU时间
long startTime = System.currentTimeMillis();
pro1 = r.exec(command);
BufferedReader in1 = new BufferedReader(new InputStream()));
String line = null;
long idleCpuTime1 = 0, totalCpuTime1 = 0;  //分别为系统启动后空闲的CPU时间和总的CPU时间
while((adLine()) != null){
if(line.startsWith("cpu")){
line = im();
log.info(line);
String[] temp = line.split("\\s+");
idleCpuTime1 = Long.parseLong(temp[4]);
for(String s : temp){
if(!s.equals("cpu")){
totalCpuTime1 += Long.parseLong(s);
}
}
log.info("IdleCpuTime: " + idleCpuTime1 + ", " + "TotalCpuTime" + totalCpuTime1);
break;
}
}
in1.close();
pro1.destroy();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
<("CpuUsage休眠时发⽣InterruptedException. " + e.getMessage());
<(sw.toString());
}
//第⼆次采集CPU时间
long endTime = System.currentTimeMillis();
pro2 = r.exec(command);
BufferedReader in2 = new BufferedReader(new InputStream()));
long idleCpuTime2 = 0, totalCpuTime2 = 0;  //分别为系统启动后空闲的CPU时间和总的CPU时间
while((adLine()) != null){
if(line.startsWith("cpu")){
line = im();
log.info(line);
String[] temp = line.split("\\s+");
idleCpuTime2 = Long.parseLong(temp[4]);
for(String s : temp){
if(!s.equals("cpu")){
totalCpuTime2 += Long.parseLong(s);
}
}
log.info("IdleCpuTime: " + idleCpuTime2 + ", " + "TotalCpuTime" + totalCpuTime2);
break;
}
}
if(idleCpuTime1 != 0 && totalCpuTime1 !=0 && idleCpuTime2 != 0 && totalCpuTime2 !=0){
cpuUsage = 1 - (float)(idleCpuTime2 - idleCpuTime1)/(float)(totalCpuTime2 - totalCpuTime1);                log.info("本节点CPU使⽤率为: " + cpuUsage);
}
in2.close();
pro2.destroy();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
<("CpuUsage发⽣InstantiationException. " + e.getMessage());
<(sw.toString());
}
return cpuUsage;
}
}
2.获取内存⼤⼩和使⽤率
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.log4j.Logger;
/**
* 采集内存使⽤率
*/
public class MemUsage{
private static Logger log = Logger(MemUsage.class);
private static MemUsage INSTANCE = new MemUsage();
private MemUsage(){
}
public static MemUsage getInstance(){
return INSTANCE;
}
/**
* Purpose:采集内存使⽤率
* @param args
* @return float,内存使⽤率,⼩于1
*/
public static float getMemUsage() {
log.info("开始收集memory使⽤率");
float memUsage = 0.0f;
Process pro = null;
Runtime r = Runtime();
try {
String command = "cat /proc/meminfo";
pro = r.exec(command);
BufferedReader in = new BufferedReader(new InputStream()));            String line = null;
int count = 0;
long totalMem = 0, freeMem = 0;
while((adLine()) != null){
log.info(line);
String[] memInfo = line.split("\\s+");
if(memInfo[0].startsWith("MemTotal")){
totalMem = Long.parseLong(memInfo[1]);
}
if(memInfo[0].startsWith("MemFree")){
freeMem = Long.parseLong(memInfo[1]);
}
memUsage = 1- (float)freeMem/(float)totalMem;
log.info("本节点内存使⽤率为: " + memUsage);
if(++count == 2){
break;
}
}
in.close();
pro.destroy();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
<("MemUsage发⽣InstantiationException. " + e.getMessage());
<(sw.toString());
}
return memUsage;
}
public static long getMemSize() {
long totalMem = 0;
Process pro = null;
Runtime r = Runtime();
try {
String command = "cat /proc/meminfo";
pro = r.exec(command);
BufferedReader in = new BufferedReader(new InputStream()));            String line = null;
int count = 0;
while((adLine()) != null){
log.info(line);
String[] memInfo = line.split("\\s+");
if(memInfo[0].startsWith("MemTotal")){
totalMem = Long.parseLong(memInfo[1]);
}
if(++count == 2){
break;
}
}
in.close();
pro.destroy();
} catch (IOException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
<("MemUsage发⽣InstantiationException. " + e.getMessage());
<(sw.toString());
}
return totalMem;
}
}
3.获取磁盘⼤⼩和使⽤率
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
public class DiskUsage {
public static double getDiskUsage() throws Exception {
double totalHD = 0;
double usedHD = 0;
double usedHD = 0;
Runtime rt = Runtime();
Process p = rt.exec("df -hl");// df -hl 查看硬盘空间
BufferedReader in = null;
try {
in = new BufferedReader(new InputStream()));
String str = null;
String[] strArray = null;
while ((str = in.readLine()) != null) {
int m = 0;
strArray = str.split(" ");
for (String tmp : strArray) {
if (im().length() == 0)
continue;
++m;
if (tmp.indexOf("G") != -1) {
if (m == 2) {
if (!tmp.equals("") && !tmp.equals("0"))
totalHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024;                        }
if (m == 3) {
if (!tmp.equals("none") && !tmp.equals("0"))
usedHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1)) * 1024;                        }
}
if (tmp.indexOf("M") != -1) {
if (m == 2) {
if (!tmp.equals("") && !tmp.equals("0"))
totalHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1));
}
if (m == 3) {
if (!tmp.equals("none") && !tmp.equals("0"))
usedHD += Double.parseDouble(tmp.substring(0, tmp.length() - 1));
}
}
}
}
} catch (Exception e) {
//logger.debug(e);
} finally {
in.close();
}
// 保留2位⼩数
double precent = (usedHD / totalHD) * 100;error parse new
BigDecimal b1 = new BigDecimal(precent);
precent = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
return precent;
}
public static double getDiskSize() throws Exception {
double totalHD = 0;
Runtime rt = Runtime();
Process p = rt.exec("df -hl");// df -hl 查看硬盘空间
BufferedReader in = null;
try {
in = new BufferedReader(new InputStream()));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。