java实现Linux服务器内存监控预警

1.需求场景

利用java程序监控Linux服务器内存变化,根据设定的内存阈值发报警邮件

2.项目环境

 普通java项目,jar形式

3.解决方法

(1)读取Linux 内存监控文件(/proc/meminfo)获取内存信息

public  static  int [] getLinuxMemInfo() throws IOException, InterruptedException  
	{  
	File file = new File("/proc/meminfo" );  
	BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(file)));  
	int [] result = new  int [ 4 ];  
	String str = null ;  
	StringTokenizer token = null ;  
	while ((str = br.readLine()) != null )  
	{  
	token = new StringTokenizer(str);  
	if (!token.hasMoreTokens())  
	continue ;  
	str = token.nextToken();  
	if (!token.hasMoreTokens())  
	continue ;  
	if (str.equalsIgnoreCase("MemTotal:" ))  
	result[0 ] = Integer.parseInt(token.nextToken());  
	else  if (str.equalsIgnoreCase("MemFree:" ))  
	result[1 ] = Integer.parseInt(token.nextToken());  
	else  if (str.equalsIgnoreCase("SwapTotal:" ))  
	result[2 ] = Integer.parseInt(token.nextToken());  
	else  if (str.equalsIgnoreCase("SwapFree:" ))  
	result[3 ] = Integer.parseInt(token.nextToken());  
	}
	return result;
	}

(2)根据设定阈值,是否发邮件预警

    int [] mem = LinuxSystemTool.getMemInfo();
    double rate = (float)mem[1]/(float)mem[0];
		String content ="比值:"+new java.text.DecimalFormat("#0.00").format(rate)+"\t总内存:"+mem[0]+"KB\t空闲物理内存:"+mem[1]+"KB\t交换分区总内存:"+mem[2]+"KB\t交换分区空闲内存:"+mem[3]+"KB";
		if(rate<=0.2){
		content+="\t系统有些累了!o(╥﹏╥)o";
		EmailUtil.sendEmail("[email protected]", "内存预警", content);
		}else{
			System.out.println("系统充满活力!^_^)";
		}

 
  (3)shell脚本 
  

#!/bin/sh
export LANG=en_US.UTF-8
cd  /test/demo
/opt/jdk/bin/java -jar /test/demo/memmonitor.jar

(4)设定定时任务

crontab -e
*/10 * * * * /test/demo/memmonitor.sh



你可能感兴趣的:(java)