java實現Linux伺服器記憶體監控預警
阿新 • • 發佈:2019-02-19
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