• 开发成功-cpu-mem监控动态折线图--dom esayui js java


    jsp 

    -------------------------------------------------------------------------------------------

    -------

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <style type="text/css">
        hr{margin: 20px 20px;}
        #main_monitor{
            background-color: #F7F7F7;
        }
        #head_monitor{
            margin:10px auto;
            width: 90%;
            height: 20%;
            background-color: #F9F9D4;
            text-align: center;
            font-size: 16px;
        }
        #body_monitor{
            margin:5px auto;
            width:100%;
            height: 80%;
            text-align: center;
            background-color: #F7F7F7;
        }
        .unit_monitor{
            text-align: center;
            margin:10px auto;
            padding:10px;
            width: 85%;
            height:300px;
            border: 1px solid #3897C5;
        }
    </style>
    <div id="main_monitor">
        <div id="head_monitor" >
            <span>服务器类型</span>
            <input>
            <span>IP地址</span>
            <input id="ip">
            <span></span>
            <input>
        </div>
        <hr>
        <div id="body_monitor">
            <div id="cpu_monitor" class="unit_monitor">
            </div>
            <div id="mem_monitor" class="unit_monitor">
            </div>
            <div id="disk_monitor" class="unit_monitor">
            </div>
            <div id="net_monitor" class="unit_monitor">
            </div>
        </div>
        
        <script type="text/javascript" src="<%=request.getContextPath() %>/ptsjs/monitor.js"></script>
    </div>

    ------------------------------------------------------------------------------------

    js

    -------------------------------------------------------------------------------------------

    $(function(){
        require.config({
                paths: {
                     echarts: 'js/chart'
                   }
            });
            var interval = 10;
            var switch_monitor = true;
            var first = 1;
            var times = 1;
            // 使用
            require(
                [
                    'echarts',
                    'echarts/chart/bar', // 使用柱状图就加载bar模块,按需加载
                    'echarts/chart/line' // 使用柱状图就加载bar模块,按需加载
                ],
                function (ec) {
                           
                    // 基于准备好的dom,初始化echarts图表
                    var myChart_cpu = ec.init(document.getElementById('cpu_monitor')); 
                    var myChart_mem = ec.init(document.getElementById('mem_monitor'));
                     series_cpu = new Array();
                     series_mem = new Array();
                     var series_cpu_data={};
                     var series_mem_data={};
                     var series_m={};//额外为mem创建一个对象,用来初始化接受ajax请求返回的data中的series
                     /*series_cpu_data_0 = new Array();
                     series_mem_data_0 = new Array();
                     series_cpu_data_1 = new Array();
                     series_mem_data_1 = new Array();*/
                     xAxis_data = new Array();
                     console.log("------------------------------------------------------1---");
                     ips = {"ip":["10.118.218.50","10.118.218.51","10.118.218.52"]};
                     console.log("-------------------------------------------------------2--");
                    /* ips = JSON.parse(ips);
                     ips = eval("("+ips+")");*/
                     console.log("-------------------------------------------------------3--");
                     /*for(var i=0;i<ips.ip.length;i++){
                         console.log("-------------------------------------------------------4--");
                         series_cpu_data[i]=new Array();
                         console.log("-------------------------------------------------------4.1--");
                         series_mem_data[i]=new Array();
                         console.log("-------------------------------------------------------4.2--");
                     }*/
                      for(var i in ips.ip){
                          var s = ips.ip[i];
                         console.log("-------------------------------------------------------4--");
                         series_cpu_data[s]=new Array();
                         console.log("-------------------------------------------------------4.1--");
                         series_mem_data[s]=new Array();
                         console.log("-------------------------------------------------------4.2--");
                         series_m[s]={};//用于存储mem_option中的的series结构,避免出现冲突。
                     }
                     console.log("-------------------------------------------------------5--"+JSON.stringify(series_cpu_data)+" "+JSON.stringify(series_mem_data));
                     ips = JSON.stringify(ips);
                     console.log("-------------------------------------------------------6--");
                    var cpu_mem_monitor = function(){
                        console.log("
    ---ips: "+ips);
                        legend_data = new Array();
                        var req_time=getDate();
                        $.ajax({
                            url : "getCpuMemData/"+interval+"/"+times+"/"+req_time,
                            type : "POST",
                            contentType : 'application/json;charset=UTF-8',
                            data : ips,
                            dataType : 'json',
                            success:function(resData, status){
                                if(resData != ""){
                                    console.log("---------------------------------------------------------");
                                    console.log("start...option....."+JSON.stringify(cpu_option));
                                    console.log("
     resData : "+JSON.stringify(resData));
                                    xAxis_data.push(resData.xAxis_data);
                                    
                                    
                                    //j用来控制多个ip时,分别用来取该ip对应的series.data数据
                                    var j=0;
                                    for(var s in resData.ip){
                                        console.log("s : "+s);
                                        legend_data.push(s);
                                        console.log("series....."+JSON.stringify(resData.ip[s].series)+"  times :"+times);
                                        console.log("series_data....."+JSON.stringify(resData.ip[s].series_data));
                                        //分别获取cpu和mem数据
                                        series_cpu_data[s].push(resData.ip[s].series_data.cpu_total);
                                        series_mem_data[s].push(resData.ip[s].series_data.mem_util);
                                        console.log("series_cpu_data["+s+"]....."+series_cpu_data[s]);
                                        console.log("series_mem_data["+s+"]....."+series_mem_data[s]);
                                        //为series_mem赋值
                                        //获取cpu和mem的series结构以及填充该结构的data值
                                        if(times == 1){
                                            console.log("resData.ip[s].series....."+JSON.stringify(resData.ip[s].series));
                                            for(var ss in resData.ip[s].series ){
                                                console.log("resData.ip[s].series+"+ss+" "+resData.ip[s].series[ss]);
                                            }
                                            //mem图标中分别为不同ip,添加对应的series
                                            for(var str in resData.ip[s].series){
                                                    series_m[s][str]=resData.ip[s].series[str];
                                                    console.log("++++++series_m["+s+"]....."+JSON.stringify(series_m[s]));
                                                }
                                            console.log("series_m....."+JSON.stringify(series_m));
                                            series_cpu.push(resData.ip[s].series);
                                            series_mem.push(series_m[s]);
                                        }
                                        console.log("series_cpu....."+JSON.stringify(series_cpu));
                                        console.log("series_mem....."+JSON.stringify(series_mem));
                                        series_cpu[j].data=series_cpu_data[s];
                                        console.log("series_cpu_data["+j+"]....."+series_cpu_data[s]);
                                        console.log("series_cpu["+j+"]. ....0."+series_cpu[j].data);
                                        console.log("series_cpu....0."+JSON.stringify(series_cpu));
                                        console.log("series_mem....0."+JSON.stringify(series_mem));
                                        series_mem[j].data=series_mem_data[s];
                                        console.log("series_mem_data["+j+"]....."+series_mem_data[s]);
                                        console.log("series_mem["+j+"].data....."+series_mem[j].data);
                                        console.log("series_cpu["+j+"]......1."+series_cpu[j].data);
                                        console.log("series_cpu....1."+JSON.stringify(series_cpu));
                                        console.log("series_mem....1."+JSON.stringify(series_mem));
                                        
                                        console.log("****xAxis_data : "+xAxis_data);    
                                        console.log("0 legend_data "+legend_data);
                                        console.log("0 xAxis_cpu_data "+xAxis_data);
                                        console.log("0 series_cpu_data "+series_cpu_data[s]);
                                        console.log("0 series_mem_data "+series_mem_data[s]);
                                        console.log("0 series_cpu.data "+series_cpu[j].data);
                                        console.log("0 series_mem.data "+series_mem[j].data);
                                        console.log("series_cpu....."+JSON.stringify(series_cpu));
                                        console.log("series_mem....."+JSON.stringify(series_mem));
                                        j++;
                                        //成功获取数据后,请求次数累加
                                             
                                    }
                                }else{
                                    clearInterval(timer_1);
                                    clearInterval(timer_2);
                                }
                                console.log("************************************************************");
                                console.log("1 legend_data "+legend_data);
                                console.log("1 series_cpu :"+series_cpu+"
     series_mem "+series_mem);
                            },
                            statusCode:{
                                404:function(){
                                    console.log("laile ");
                                    clearInterval(timer_1);
                                    clearInterval(timer_2);
                                },
                                500:function(){
                                    console.log("laile ");
                                    clearInterval(timer_1);
                                    clearInterval(timer_2);
                                },
                                405:function(){
                                    console.log("laile ");
                                    clearInterval(timer_1);
                                    clearInterval(timer_2);
                                }
                            },
                            error:function(XMLHttpRequest, textStatus, errorThrown){
                                         console.log("----XMLHttpRequest.status------"+XMLHttpRequest.status);
                                         console.log("----XMLHttpRequest.readyState------"+XMLHttpRequest.readyState);
                                         console.log("----textStatus------"+textStatus);
                                      //通常情况下textStatus和errorThrown只有其中一个包含信息
                                         console.log(this);   //调用本次ajax请求时传递的options参数
                                         clearInterval(timer_1);
                                        clearInterval(timer_2);
                                        $.messager.alert('警告','获取监控数据失败,请检查网络或者查看该ip是否存于后台数据库');  
                            }
                        });
                        
                        //cpu统计
                        cpu_option = {
                                    title : {
                                            text: 'CPU资源使用监控',
                                           subtext: '性能环境'
                                    },
                                    tooltip: {
                                        show: true
                                    },
                                    legend: {
                                        data:[] //"10.118.218.50"
                                    },
                                    dataZoom: {
                                        show: true
                                    },
                                    xAxis : [
                                        {
                                            name : '时间',
                                            nameLocation : 'end' ,
                                            nameGap : 10,
                                            type : 'category',//category time
                                            data :[]//["10","15","20","25","30","35",'40','45','50','55','60','65','70']
                                        }
                                    ],
                                    yAxis : [
                                        {    
                                            name : 'CPU 利用率(单位:%)',//
                                            nameLocation : 'end' ,
                                            nameGap :20,
                                            //splitNumber :5,
                                            type : 'value'
                                        }
                                    ],
                                    series    : [] //[{"name":"10.118.218.50","data":["5","10","5","10","5","10","5","10"],"type":"line"}]
                                    /*series : [
                                        {
                                            "name":"10.118.218.50",
                                            "type":"line",
                                            "data":['5', '20', '40', '10', '10', '20']
                                        },
                                        {
                                            "name":"10.118.218.51",
                                            "type":"line",
                                            "data":['15', '30', '50', '20', '18', '28']
                                        },
                                        {
                                            "name":"10.118.218.52",
                                            "type":"line",
                                             "data":['25', '20', '40', '27', '65', '36']
                                        }
                                    ]*/
                                };
                        //mem统计
                        mem_option = {
                                    title : {
                                            text: 'MEM资源使用监控',
                                           subtext: '性能环境'
                                    },
                                    tooltip: {
                                        show: true
                                    },
                                    legend: {
                                        data:[] //"10.118.218.50"
                                    },
                                    dataZoom: {
                                        show: true
                                    },
                                    xAxis : [
                                        {
                                            name : '时间',
                                            nameLocation : 'end' ,
                                            nameGap : 10,
                                            type : 'category',//category time
                                            data :[]//["10","15","20","25","30","35",'40','45','50','55','60','65','70']
                                        }
                                    ],
                                    yAxis : [
                                        {    
                                            name : 'MEM 利用率(单位:%)',//
                                            nameLocation : 'end' ,
                                            nameGap :20,
                                            //splitNumber :5,
                                            type : 'value'
                                        }
                                    ],
                                    series    : [] //[{"name":"10.118.218.50","data":["5","10","5","10","5","10","5","10"],"type":"line"}]
                                };
                        
                        //检查数据是否获取
                        timer_2=setInterval(checkData,5000);
                        function checkData(){
                            //档xAxis_data不为空时则此时可以朝图标灌入数据
                            if(xAxis_data.length >0){
                                console.log("来了:"+legend_data+"  "+xAxis_data);
                                //设置处理后的值到option中
                                cpu_option.legend.data = legend_data;
                                cpu_option.xAxis[0].data =xAxis_data;
                                cpu_option.series=series_cpu;
                                mem_option.legend.data = legend_data;
                                mem_option.xAxis[0].data =xAxis_data;
                                mem_option.series=series_mem;
    //                            for(var i=0;i<series_cpu.size;i++){
    //                                option.series[i]=series_cpu[i];
    //                            }
                                 console.log("4"+JSON.stringify(cpu_option.legend));
                                 console.log("4 "+JSON.stringify(cpu_option.series));
                                 console.log("************* "+JSON.stringify(cpu_option.series));
                                 console.log("++++
    "+JSON.stringify(cpu_option));
                                 console.log("----
    "+JSON.stringify(mem_option));
    
                                  // 为echarts对象加载数据 
                                myChart_cpu.setOption(cpu_option);
                                myChart_mem.setOption(mem_option);
                                clearInterval(timer_2);
                                //页面开关,当停止监控时,不再发起监控请求。
                                if(!switch_monitor){
                                    clearInterval(timer_1);
                                }
                                times++;
                            }
                        };
                        console.log("5 legend_data "+legend_data);
                        console.log("5 series_cpu_data "+JSON.stringify(series_cpu_data));
                    };
                    if(switch_monitor){
                        if(first == 1){
                        cpu_mem_monitor();
                            first=0;
                        }
                        timer_1=setInterval(cpu_mem_monitor,interval*1000);
                    } 
                    /*--2--*/
                     // 基于准备好的dom,初始化echarts图表
                    var myChart_disk = ec.init(document.getElementById('disk_monitor')); 
                    
                    var disk_option = {
                        tooltip: {
                            show: true
                        },
                        legend: {
                            data:['统计']
                        },
                        xAxis : [
                            {
                                type : 'category',
                                data : ["顺手付","理财","银企直连","小贷","顺丰卡"]
                            }
                        ],
                        yAxis : [
                            {
                                type : 'value'
                            }
                        ],
                        series : [
                            {
                                "name":"系统",
                                "type":"bar",
                                "data":[5, 20, 40, 10, 10]
                            }
                        ]
                    };
            
                    // 为echarts对象加载数据 
                    myChart_disk.setOption(disk_option); 
                }
            );
            //获取当前监控时间点,实际监控数据与时间点存在0-5秒的延迟
            var getDate = function(){
                var d = new Date();
                var con = '';
                var year = d.getFullYear();
                var month = d.getMonth()+1+con;
                var date = d.getDate()+con;
                var hour = d.getHours()+con;
                var minute = d.getMinutes()+con;
                var second = d.getSeconds()+con;
                console.log("----month.length   "+month.length)
                if( month.length < 2 ) month = "0"+month;
                if( date.length < 2 ) date = "0"+date;
                if( hour.length < 2 ) hour = "0"+hour;
                if( minute.length < 2 ) minute = "0"+minute;
                if( second.length < 2 ) second = "0"+second;
                console.log("request time :"+ year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second);
                return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
            };
    });

    -------------------------------------------------------------------------------------------

    java

    -------------------------------------------------------------------------------------------

    package com.sfpay.pts.controller;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import com.sfpay.pts.model.MachineInfoModel;
    import com.sfpay.pts.util.ContextParaInitializeUtil;
    import com.sfpay.pts.util.MonitorUtil;
    
    @Controller
    @RequestMapping("/")
    public class PerformanceMonitorController {
        private Logger log = LoggerFactory
                .getLogger(PerformanceMonitorController.class);
        private static JSONObject monitor_data;
        private ContextParaInitializeUtil cpiUtil = new ContextParaInitializeUtil();
        @RequestMapping("nowMonitor.action")
        public String toNowMonitorPage() {
            log.info("跳转进入监控页面");
            return "/resource/nowMonitor";
        }
    
        @RequestMapping("historyMonitor.action")
        public String toHistoryMonitorPage() {
            log.info("跳转进入监控页面");
            return "/resource/historyMonitor";
        }
        
        public static void main(String[] args) {
            PerformanceMonitorController p = new PerformanceMonitorController();
            HttpServletRequest request = null;
            JSONObject json = new JSONObject();
            String[] ip = {"10.118.218.50","10.118.218.51"};
            json.put("ip", ip);
            p.getCpuMemMonitorData(request, 1, 20 , "2015-07-21 10:10:10",json);
        }
        
        
        @RequestMapping(value = "getCpuMemData/{interval}/{times}/{req_time}")//
        @ResponseBody
        public JSONObject getCpuMemMonitorData(HttpServletRequest request,@PathVariable("interval") int interval,
                @PathVariable("times") int times,
                @PathVariable("req_time") String req_time,
                @RequestBody JSONObject ip) {
                log.info("CPU 监控频率为 " + interval + "秒;监控次数:" + times + " ,监控请求时间 "
                        + req_time+" ;所监控IP: "+ip.toString());//
                // 最终返回的对象
                JSONObject json = new JSONObject();
                // json的value,可以包含多个ip的数据
                JSONObject ip_data = new JSONObject();
                // 一个ip_data包含多个option,一个option包含1个ip对应的所有监控数据
                JSONObject option ;
                // option包含监控数据结构
                JSONObject series = null;
                // 定义xAxis和series的动态列表以及数组,然后动态列表转成数组
                String xAxis_data = req_time.split(" ")[1]; // "xAxis_data":[],
                // 用于初始化series对象中的data属性
                String[] series_datas = new String[0];
                //额外封装一个series_data对象,用于封装监控的数据
                JSONObject series_data ;
                
                //存储被监控机器信息
                MachineInfoModel miModel;
                //存储cpu监控信息
                Map<String,String> cpu_mem_map ;
                //监控工具对象
                MonitorUtil m = new MonitorUtil();
                String ip_exist = "no";
                for(Object s :ip.getJSONArray("ip")){
                    //存放监控数据
                    series_data = new JSONObject();
                    //存放前端echarts需要的数据
                    series = new JSONObject();
                    //存放多个series
                    option = new JSONObject();
                    //存放监控结果
                    cpu_mem_map = new HashMap<String,String>();
                    //创建存放一个ip对应的机器信息对象
                    miModel = new MachineInfoModel();
                    //获取ip的详细信息
                    miModel = cpiUtil.getIpinfo(s.toString());
                    //如果获取ip后该对象ip信息为空,说明该ip在后台数据库中不存在
                    if(!miModel.getIp().equals("")){
                        cpu_mem_map=m.getCpuMemMonitor(miModel);
                        ip_exist = "yes";
                    }
                    //把获取的监控信息cpu_mem_map从map对象转化成json对象
                    series_data = JSONObject.fromObject(cpu_mem_map);
                    series.put("name", s.toString());
                    series.put("type", "line");
                    series.put("smooth", true);
                    series.put("data", series_datas);
                    // "series":{"name":"10.118.218.50","data":[],"type":"line"},
                    log.debug("获取 "+s.toString()+"返回到页面的series信息:"+series.toString()+" "+series.get("data")+" "+series_datas.toString());
                    // series 和 series_data放入到option中
                    // 一个ip对应一个option
                    option.put("ip_exist",ip_exist );
                    option.put("series", series);
                    option.put("series_data", series_data);
                    ip_data.put(s.toString(), option);
                    log.debug("获取 "+s.toString()+"返回到页面的option信息:"+ip_data.toString());
                }
                    
                // 一个ip对应一个data,最终一个json包含多个ip
                json.put("ip", ip_data);
                json.put("xAxis_data", xAxis_data);
                    /*json对象格式如下*/
                    /*
                     {
                        "xAxis_data":"17:27:52",
                        "ip":
                                {
                                    "10.118.218.50":
                                        {
                                            "series":{"name":"10.118.218.50","type":"line"},
                                            "ip_exist":"yes",
                                            "series_data":"1"
                                        },
                                        "10.118.218.51":
                                        {
                                            "series":{"name":"10.118.218.51","type":"line"},
                                            "ip_exist":"yes",
                                            "series_data":"1"
                                        }
                                }
                    }                  
                     */
                    System.out.println(monitor_data);
                    monitor_data = ip_data;
                    log.info("monitor_data : " + monitor_data.toString());
                    log.info("*******最终返回页面数据*******"+json.toString());
            return json;
        }
        
    }

    -------------------------------------------------------------------------------------------

  • 相关阅读:
    Eclipse将引用了第三方jar包的Java项目打包成jar文件的两种方法
    【提供笔试面试题参考】阿里巴巴,淘宝技术部,针对21届应届生的内推机会
    谈谈我眼中的CSDN吧
    我的2014碎碎念—学习篇、实习篇、工作篇、生活篇
    推荐几款我一直在用的chrome插件(下)
    推荐几款我一直在用的chrome插件(上)
    逛自己的微博,回顾曾经的那个“我”
    Java五道输出易错题解析(避免小错误)
    程序员和产品经理是怎么互相看的?贬低还是赞扬?
    现实中如何评判路遥《人生》中的高加林?
  • 原文地址:https://www.cnblogs.com/anruy/p/5760507.html
Copyright © 2020-2023  润新知