來源:http://www.cnblogs.com/haifg/p/3217699.htmljavascript
最近項目須要監控服務器cpu的利用率,並作成動態圖。在網上查找了一些資料,最終選擇了HighChartS來作動態圖。html
HIghChartS官網:http://www.highcharts.com/java
HighCharts Demo:http://www.highcharts.com/demo/jquery
項目中參考的Demo:http://www.highcharts.com/demo/dynamic-updateajax
完成這個cpu利用率的動態圖,作了一個小的Demo,分爲三層:界面層(jsp),控制層(servlet),模型層(javabean)。json
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script src="js/jquery.min.js"></script><!-- 1.8.2 --> <script type="text/javascript"> $(function() { Highcharts.setOptions({ global: { useUTC: false } }); //聲明報表對象 chart = new Highcharts.Chart({ chart: { renderTo: 'container', defaultSeriesType: 'spline', marginRight: 10 }, title: { text: 'CPU使用率動態曲線圖' }, xAxis: { title: { text: '時間' }, //linear" or "datetime" type: 'datetime', //座標間隔 tickPixelInterval: 150 }, yAxis: { title: { text: '使用率' }, //指定y=3直線的樣式 plotLines: [ { value: 0, width: 1, color: '#808080' } ] }, //鼠標放在某個點上時的提示信息 //dateFormat,numberFormat是highCharts的工具類 tooltip: { formatter: function() { return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' + Highcharts.numberFormat(this.y, 4); } }, //曲線的示例說明,像地圖上得圖標說明同樣 legend: { enabled: true }, //把曲線圖導出成圖片等格式 exporting: { enabled: true }, //放入數據 series: [ { name: 'CPU使用率', data: (function() { // 初始化數據 var data = [], time = (new Date()).getTime(), i; for (i = -19; i <= 0; i++) { data.push({ x: time + i * 1000, y: Math.random() * 100 }); } return data; })() } ] }); getCpuInfo(); }); function getCpuInfo(){ $.ajax({ url: "GetCpu", type: "post", dataType:'json', success: function(data){ chart.series[0].addPoint([data.x,data.y], true, true); } }); } setInterval(getCpuInfo, 1000); </script> </head> <body> <script src="js/highcharts.js"></script> <script src="js/exporting.js"></script> <div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div> </body> </html>
package com.highcharts.action; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import com.highcharts.dao.SnmpGetAsyn; public class GetCpu extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String ip = "219.230.155.67"; String community = "public"; List<String> oidList = new ArrayList<String>(); //ssCpuRawUser oidList.add(".1.3.6.1.4.1.2021.11.50.0"); //ssCpuRawNice oidList.add(".1.3.6.1.4.1.2021.11.51.0"); //ssCpuRawSystem oidList.add(".1.3.6.1.4.1.2021.11.52.0"); //ssCpuRawIdle oidList.add(".1.3.6.1.4.1.2021.11.53.0"); //ssCpuRawWait oidList.add(".1.3.6.1.4.1.2021.11.54.0"); //ssCpuRawKernel //oidList.add(".1.3.6.1.4.1.2021.11.55.0"); //ssCpuRawInterrupt oidList.add(".1.3.6.1.4.1.2021.11.56.0"); //ssCpuRawSoftIRQ oidList.add("1.3.6.1.4.1.2021.11.61.0"); // 異步採集數據 List cpuData = SnmpGetAsyn.snmpAsynGetList(ip, community, oidList); double ssCpuRawUser = Double.parseDouble(cpuData.get(0).toString()); double ssCpuRawNice = Double.parseDouble(cpuData.get(1).toString()); double ssCpuRawSystem = Double.parseDouble(cpuData.get(2).toString()); double ssCpuRawIdle = Double.parseDouble(cpuData.get(3).toString()); double ssCpuRawWait = Double.parseDouble(cpuData.get(4).toString()); double ssCpuRawInterrupt = Double.parseDouble(cpuData.get(5).toString()); double ssCpuRawSoftIRQ = Double.parseDouble(cpuData.get(6).toString()); Map<String, Object> jsonMap = new HashMap<String, Object>();//定義map double cpuRatio = 100*(ssCpuRawUser+ssCpuRawNice+ssCpuRawSystem+ssCpuRawWait+ssCpuRawInterrupt+ssCpuRawSoftIRQ)/(ssCpuRawUser+ssCpuRawNice +ssCpuRawSystem+ssCpuRawIdle+ssCpuRawWait+ssCpuRawInterrupt+ssCpuRawSoftIRQ); System.out.println("CPU利用率:"+cpuRatio); jsonMap.put("y",cpuRatio); jsonMap.put("x", new Date().getTime()); JSONObject result = JSONObject.fromObject(jsonMap);//格式化result 必定要是JSONObject out.print(result.toString()); out.flush(); out.close(); } }
package com.highcharts.dao; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.snmp4j.CommunityTarget; import org.snmp4j.PDU; import org.snmp4j.Snmp; import org.snmp4j.event.ResponseEvent; import org.snmp4j.event.ResponseListener; import org.snmp4j.mp.SnmpConstants; import org.snmp4j.smi.Address; import org.snmp4j.smi.GenericAddress; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping; /** * 演示:異步GET OID值 * * blog http://www.micmiu.com * * @author Michael * */ public class SnmpGetAsyn { public static final int DEFAULT_VERSION = SnmpConstants.version2c; public static final String DEFAULT_PROTOCOL = "udp"; public static final int DEFAULT_PORT = 161; public static final long DEFAULT_TIMEOUT = 3 * 1000L; public static final int DEFAULT_RETRY = 3; /** * 建立對象communityTarget * * @param targetAddress * @param community * @param version * @param timeOut * @param retry * @return CommunityTarget */ public static CommunityTarget createDefault(String ip, String community) { Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip + "/" + DEFAULT_PORT); CommunityTarget target = new CommunityTarget(); target.setCommunity(new OctetString(community)); target.setAddress(address); target.setVersion(DEFAULT_VERSION); target.setTimeout(DEFAULT_TIMEOUT); // milliseconds target.setRetries(DEFAULT_RETRY); return target; } /** * 異步採集信息 * * @param ip * @param community * @param oid */ public static List snmpAsynGetList(String ip, String community, List<String> oidList) { final List cpuData = new ArrayList(); CommunityTarget target = createDefault(ip, community); Snmp snmp = null; try { DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping(); snmp = new Snmp(transport); snmp.listen(); PDU pdu = new PDU(); for (String oid : oidList) { pdu.add(new VariableBinding(new OID(oid))); } final CountDownLatch latch = new CountDownLatch(1); ResponseListener listener = new ResponseListener() { public void onResponse(ResponseEvent event) { ((Snmp) event.getSource()).cancel(event.getRequest(), this); PDU response = event.getResponse(); PDU request = event.getRequest(); System.out.println("[request]:" + request); if (response == null) { System.out.println("[ERROR]: response is null"); } else if (response.getErrorStatus() != 0) { System.out.println("[ERROR]: response status" + response.getErrorStatus() + " Text:" + response.getErrorStatusText()); } else { System.out.println("Received response Success!"); for (int i = 0; i < response.size(); i++) { VariableBinding vb = response.get(i); /* System.out.println(vb.getOid() + " = " + vb.getVariable());*/ cpuData.add(vb.getVariable()); } System.out.println("SNMP Asyn GetList OID finished. "); latch.countDown(); } } }; pdu.setType(PDU.GET); snmp.send(pdu, target, null, listener); System.out.println("asyn send pdu wait for response..."); boolean wait = latch.await(30, TimeUnit.SECONDS); System.out.println("latch.await =:" + wait); snmp.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("SNMP Asyn GetList Exception:" + e); } return cpuData; } public static void main(String[] args) { String ip = "219.230.155.67"; String community = "public"; List<String> oidList = new ArrayList<String>(); //ssCpuRawUser oidList.add(".1.3.6.1.4.1.2021.11.50.0"); //ssCpuRawNice oidList.add(".1.3.6.1.4.1.2021.11.51.0"); //ssCpuRawSystem oidList.add(".1.3.6.1.4.1.2021.11.52.0"); //ssCpuRawIdle oidList.add(".1.3.6.1.4.1.2021.11.53.0"); //ssCpuRawWait oidList.add(".1.3.6.1.4.1.2021.11.54.0"); //ssCpuRawInterrupt oidList.add(".1.3.6.1.4.1.2021.11.56.0"); //ssCpuRawSoftIRQ oidList.add("1.3.6.1.4.1.2021.11.61.0"); // 異步採集數據 List cpuData = SnmpGetAsyn.snmpAsynGetList(ip, community, oidList); double ssCpuRawUser = Double.parseDouble(cpuData.get(0).toString()); double ssCpuRawNice = Double.parseDouble(cpuData.get(1).toString()); double ssCpuRawSystem = Double.parseDouble(cpuData.get(2).toString()); double ssCpuRawIdle = Double.parseDouble(cpuData.get(3).toString()); double ssCpuRawWait = Double.parseDouble(cpuData.get(4).toString()); double ssCpuRawInterrupt = Double.parseDouble(cpuData.get(5).toString()); double ssCpuRawSoftIRQ = Double.parseDouble(cpuData.get(6).toString()); double cpuRatio = 100*(ssCpuRawUser+ssCpuRawNice+ssCpuRawSystem+ssCpuRawWait+ssCpuRawInterrupt+ssCpuRawSoftIRQ)/(ssCpuRawUser+ssCpuRawNice +ssCpuRawSystem+ssCpuRawIdle+ssCpuRawWait+ssCpuRawInterrupt+ssCpuRawSoftIRQ); System.out.println("CPU利用率:"+cpuRatio); } }
瀏覽器訪問:http://localhost:8080/HighChartTest/highChartsTest.jsp瀏覽器
效果如圖(截取一個靜態的圖):服務器
至此,基本的效果已經出來,可是還有些地方須要完善。app
1、cpu的利用率的計算方法須要改變: dom
一、 採樣兩個足夠短的時間間隔的Cpu快照,分別記做t1,t2,其中t一、t2的結構均爲:
(user、nice、system、idle、iowait、irq、softirq、stealstolen、guest)的9元組;
二、 計算總的Cpu時間片totalCpuTime
a) 把第一次的全部cpu使用狀況求和,獲得s1;
b) 把第二次的全部cpu使用狀況求和,獲得s2;
c) s2 - s1獲得這個時間間隔內的全部時間片,即totalCpuTime = j2 - j1 ;
三、計算空閒時間idle
idle對應第四列的數據,用第二次的第四列 - 第一次的第四列便可
idle=第二次的第四列 - 第一次的第四列
六、計算cpu使用率
pcpu =100* (total-idle)/total
2、代碼須要重構
ps:這個demo多有不足之處,望指出。完善版的之後奉上。