【echarts】echarts开发流程详解
首先是封裝echarts option和echarts series的兩個POJO類:
EchartsOptions.java
package com.hollycrm.hollyuniproxy.opration.svcmonitor.entities; import java.util.ArrayList; import java.util.List; import java.util.Map;/*** echarts圖表封裝options數據的POJO類* @author lmb_**/ public class EchartsOptions {public List<String> legend = new ArrayList<String>();//圖例public List<String> category = new ArrayList<String>();//橫坐標 public List<List<String>> categoryList = new ArrayList<List<String>>();//橫坐標public List<String> timeline = new ArrayList<String>();//時間軸public List<EchartsSeries> seriesLeft = new ArrayList<EchartsSeries>();//左側縱坐標 public List<EchartsSeries> seriesRight = new ArrayList<EchartsSeries>();//右側縱坐標 public List<List<EchartsSeries>> series = new ArrayList<List<EchartsSeries>>();public List<Map<String, Object>> seriesPie = new ArrayList<Map<String,Object>>();public EchartsOptions(List<String> legend, List<String> category,List<List<EchartsSeries>> series) {super();this.legend = legend;this.category = category;this.series = series;}public EchartsOptions(List<String> legend, List<String> category,List<String> timeline, List<EchartsSeries> seriesLeft,List<EchartsSeries> seriesRight) {super();this.legend = legend;this.category = category;this.timeline = timeline;this.seriesLeft = seriesLeft;this.seriesRight = seriesRight;}public EchartsOptions(List<String> legend, List<String> category,List<String> timeline, List<List<EchartsSeries>> series) {super();this.legend = legend;this.category = category;this.timeline = timeline;this.series = series;}public EchartsOptions(List<String> legend, List<String> category,List<List<String>> categoryList, List<String> timeline,List<EchartsSeries> serieLeft, List<EchartsSeries> serieRight,List<List<EchartsSeries>> series) {this.legend = legend;this.category = category;this.categoryList = categoryList;this.timeline = timeline;this.seriesLeft = seriesLeft;this.seriesRight = serieRight;this.series = series;}public EchartsOptions(List<String> legend,List<Map<String, Object>> seriesPie) {super();this.legend = legend;this.seriesPie = seriesPie;} }EchartsSeries.java::
package com.hollycrm.hollyuniproxy.opration.svcmonitor.entities; import java.util.List;/*** echarts圖表封裝series數據的POJO類* @author lmb_**/ public class EchartsSeries {public String name; public String type; public List<Double> data;//不能用String,否則前臺不能正常顯示(特別是在做數學運算的時候) public EchartsSeries(String name, String type, List<Double> data) {super();this.name = name;this.type = type;this.data = data;} }流程:前臺發送請求調用后臺方法將需要的數據查回來之后,將數據按照定義的兩個POJO類的形式進行數據封裝,之后傳給前臺,在前臺相應的地方加載相應的數據(通過名稱legend、series、timeline等進行識別).
以服務器監控應用總體情況的并發數折線圖為例:
1、在realConcurrencyData.js中的URL中配置請求地址,請求成功之后將對應echarts折線圖的圖例、橫坐標以及縱坐標分別加載到前臺的圖表中。
realConcurrencyData.js:
/*** 服務器運行總體情況* @param echarts* @param divId* @param ctx*/ HollyProxy.ServerWorkMonitor.prototype.realConcurrencyData= function(echarts,divId,ctx){ // alert("HollyProxy.ServerWorkMonitor.prototype.realConcurrencyData " + ctx);var myChart = echarts.init(document.getElementById(divId)); myChart.showLoading({ text : "圖表數據正在努力加載..." }); //定義圖表options var options = {tooltip : {trigger: 'axis'},toolbox: {show : false,feature : {dataView : {show: true, readOnly: false},saveAsImage : {show: true}}},calculable : true,dataZoom: {show: true,start : 60,end : 100,height : 20},legend: {textStyle:{color:'white'},data:['并發數','每分鐘訪問量']},xAxis : [{type : 'category',axisLabel :{show:true,textStyle:{color:'white'}},splitLine:{show:false},data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']}],yAxis : [{type : 'value',name : '并發數',splitLine:{show:false},axisLabel : {show:true,textStyle:{color:'white'}, // formatter: '{value}'}},{type : 'value',name : '每分鐘訪問量',splitLine:{show:false},axisLabel : {show:true,textStyle:{color:'white'}, // formatter: '{value}'}}],series : [{name:'并發數',type:'line',symbol:'none',data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],markPoint : {data : [{type : 'max', name: '最大值'},{type : 'min', name: '最小值'}]}},{name:'每分鐘訪問量',type:'line',symbol:'none',yAxisIndex: 1,data:[2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2],markPoint : {data : [{type : 'max', name: '最大值'},{type : 'min', name: '最小值'}]}}]};//設置延遲setTimeout( function getChartData() { //獲得圖表的options對象 //通過Ajax獲取數據 $.ajax({url:ctx+ "/rest/qryRealConcurrencyData",type:'POST',dataType:'json',success : function(result) { if (result) { //請求成功將數據設置到相應的位置上 // options.options[0].legend.data = result[0].legend; options.legend.data = ["并發數","每分鐘訪問量"]; console.info("options.legend.data" + options.legend.data);options.xAxis[0].data = result.category; // options.xAxis[0].data = ["0:01","0:02","0:03","0:04","0:05","0:06","0:07","0:08","0:09","0:10","0:11","0:12","0:13","0:14","0:15","0:16","0:17","0:18","0:19","0:20","0:21","0:22","0:23","0:24","0:25","0:26","0:27","0:28","0:29","0:30","0:31","0:32","0:33","0:34","0:35","0:36","0:37","0:38","0:39","0:40","0:41","0:42","0:43","0:44","0:45","0:46","0:47","0:48","0:49","0:50","0:51","0:52","0:53","0:54","0:55","0:56","0:57","0:58","0:59","1:00"];console.info("options.options[0].xAxis[0].data" + options.xAxis[0].data);options.series[0].data = result.series[0][0].data;//并發量options.series[1].data = result.series[1][0].data;//每秒訪問量 // options.series[0].data= ["9800","4000","9000","6000","5000","6000","7000","6000","5000","4000","9800","7000","7900","6000","4000","5000","6000","8000","5000","6000","6000","5000","6000","7000","9800","4000","9000","6000","5000","6000","7000","6000","5000","4000","9800","7000","7900","6000","4000","5000","9800","4000","9000","6000","5000","6000","7000","6000","5000","4000","9800","7000","7900","6000","4000","5000","6000","8000","5000","6000"]; // options.series[1].data = ["8000","1000","9000","1000","1000","1000","7000","1000","1000","1000","9800","1000","7900","1000","1000","1000","1000","8000","1000","1000","1000","1000","1000","1000","8000","1000","9000","1000","1000","1000","7000","1000","1000","1000","9800","1000","7900","1000","1000","1000","9800","4000","9000","6000","5000","6000","7000","6000","5000","4000","9800","7000","7900","6000","4000","5000","6000","8000","5000","6000"];console.info("options.options[0].series[0].data" + options.series[0].data);console.info("options.options[0].series[1].data" + options.series[1].data);myChart.hideLoading(); console.log("成功率options" + JSON.stringify(options));myChart.setOption(options); } }, error : function(xmlHttpRequest,errorMsg,exceptionObject) { // alert('xmlHttpRequest>>>>>' + xmlHttpRequest);myChart.hideLoading(); } });} ,100); };2、InterfaceAccessEchartsController.java中的qryRealConcurrencyData方法即為上面JS請求的后臺方法,在該方法中調用業務邏輯層UniformDetailDao.java中的方法查詢實時并發數據。
InterfaceAccessEchartsController.java:
/*** 并發數 + 每秒訪問量 (服務器監控應用總體情況)* @param json* @param req* @return* @throws ParseException */@ RequestMapping(value= "/qryRealConcurrencyData",produces="text/plain;charset=UTF-8")public @ResponseBody String qryRealConcurrencyData(String json,HttpServletRequest req) throws ParseException {EchartsOptions superveneData = UniformDetailDao.qryRealConcurrencyDetail(adminService);return JSON.toJSONString(superveneData);}3、業務邏輯層UniformDetailDao.java中的方法查詢實時并發數據,之后調用EchartsDataUtil.java對查回的數據進行封裝。
UniformDetailDao.java:
/*** 統一接口明細查詢業務邏輯類* @author lmb_**/ public class UniformDetailDao {private static final Log logger = LogFactory.getLog(InterfaceAccessController.class);/*** 查詢并發數 + 每秒訪問量 (服務器監控應用總體情況)明細* @param adminService* @return* @throws ParseException*/@SuppressWarnings({ "unchecked", "rawtypes" })public static EchartsOptions qryRealConcurrencyDetail(AdminService adminService) throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Calendar calendar = Calendar.getInstance();//HOUR_OF_DAY 指示一天中的小時calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);String startDate = sdf.format(calendar.getTime());calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);List<Map<String, Object>> superveneDatas = new ArrayList<Map<String, Object>>();List args = new ArrayList<>();String sql="select to_char(modify_time,'yyyy-MM-dd HH24:mi') modify_time,sum(supervene_count) supervene_count,sum(total_count) total_count from TBL_MONITOR_HEARTBEAT_HIS " +"where modify_time >= to_date(?,'yyyy-MM-dd HH24:mi:ss') and modify_time <= to_date(?,'yyyy-MM-dd HH24:mi:ss') group by to_char(modify_time,'yyyy-MM-dd HH24:mi')";args.add(sdf.format(calendar.getTime())); args.add(sdf.format(new Date()));//轉換為可執行的SQLString executeSQL=DaoUtil.converseQesmarkSQL(sql, args);logger.debug("查詢應用總體情況并發量及每分鐘訪問量的可執行sql>>>>>>>" + executeSQL);superveneDatas=adminService.findBySql(sql, args.toArray());logger.debug("執行sql語句查回的list集合 superveneDatas>>" + superveneDatas);EchartsOptions superveneData = EchartsDataUtil.getEchartsSuperveneData(superveneDatas,startDate,sdf.format(new Date()));return superveneData;} }4、在EchartsDataUtil.java中對數據按照EchartsOptions.java和EchartsSeries.java定義的echarts格式進行封裝。
EchartsDataUtil.java:
package com.hollycrm.hollyuniproxy.opration.util;import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map;import org.apache.commons.lang.StringUtils;import com.hollycrm.hollyuniproxy.opration.svcmonitor.entities.EchartsOptions; import com.hollycrm.hollyuniproxy.opration.svcmonitor.entities.EchartsSeries; import com.hollycrm.hollyuniproxy.util.ApDateTime; import com.itextpdf.text.pdf.PdfStructTreeController.returnType; import com.jcraft.jsch.Logger;/*** 組裝echarts圖表的工具類* * @author lmb_* */ public class EchartsDataUtil {/*** 獲取應用的并發數及每秒訪問量* @param superveneDatas* @param startDate* @param endDate* @return* @throws ParseException */public static EchartsOptions getEchartsSuperveneData(List<Map<String, Object>> list, String startDate,String endDate) throws ParseException {System.out.println(">>>into EchartsUtil.getEchartsSuperveneData()>>>>");List<EchartsOptions> echartsDataList = new ArrayList<EchartsOptions>();EchartsOptions superveneData = querySuperveneData(list, startDate, endDate);// 成功率圖表echartsDataList.add(superveneData);System.out.println("getEchartsSuperveneData>>echartsDataList>" + echartsDataList);return superveneData;} /*** 封裝應用的并發數和每秒訪問量* @param list* @param startDate* @param endDate* @return* @throws ParseException*/private static EchartsOptions querySuperveneData(List<Map<String, Object>> list, String startDate, String endDate) throws ParseException {List<String> legend = new ArrayList<String>();// 圖例List<String> category = new ArrayList<String>();// 橫坐標List<String> categoryForSeries = new ArrayList<String>();yyyy-MM-dd HH:mmList<String> categoryForSeriesLastMin = new ArrayList<String>();yyyy-MM-dd HH:mmList<List<EchartsSeries>> series = new ArrayList<List<EchartsSeries>>();// 縱坐標category = installCategory(startDate, endDate);//HH:mmcategoryForSeries = installCategoryForSeries(startDate, endDate);categoryForSeriesLastMin = installCategoryForSeriesLastMin(startDate, endDate);series = installSeries(startDate, endDate, list,categoryForSeriesLastMin,categoryForSeries);EchartsOptions superveneData = new EchartsOptions(legend, category, series);System.out.println("querySuperveneData>>superveneData " + superveneData);return superveneData;} /*** 封裝并發數和每秒訪問量的橫坐標(HH:mm)* @param startDate* @param endDate* @return* @throws ParseException*/private static List<String> installCategory(String startDate, String endDate) throws ParseException { // 一個小時前的時間: 2015-12-16 15:34:33 // 當前的時間: 2015-12-16 16:34:33List<String> category = new ArrayList<String>();String[] categoryStr = new String[60];// 橫坐標顯示數據SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");for (int i = 0; i < categoryStr.length; i++) {Calendar calendar = Calendar.getInstance(); calendar.setTime(sdf.parse(startDate));categoryStr[i] = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE); //HH:mm//將startDate的時間設置為下一分鐘calendar.add(Calendar.MINUTE, 1);startDate = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "" + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);//yyyy-MM-dd HH:mm:ss}category.addAll(Arrays.asList(categoryStr));return category;} /*** 封裝并發數和每秒訪問量的橫坐標(yyyy-MM-dd HH:mm:ss)* @param startDate* @param endDate* @return* @throws ParseException*/private static List<String> installCategoryForSeries(String startDate,String endDate) throws ParseException {List<String> categoryForSeries = new ArrayList<String>();String[] categoryForSeriesStr = new String[60];SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");for (int i = 0; i < categoryForSeriesStr.length; i++) {Calendar calendar = Calendar.getInstance(); calendar.setTime(sdf.parse(startDate));categoryForSeriesStr[i]= sdf.format(ApDateTime.getDate(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "" + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE),"yyyy-MM-dd HH:mm"));//yyyy-MM-dd HH:mm//將startDate的時間設置為下一分鐘calendar.add(Calendar.MINUTE, 1);startDate = sdf.format(ApDateTime.getDate( calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "" + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE),"yyyy-MM-dd HH:mm"));//yyyy-MM-dd HH:mm:ss}categoryForSeries.addAll(Arrays.asList(categoryForSeriesStr));System.out.println(" installCategoryForSeries categoryForSeries " + categoryForSeries);return categoryForSeries;} /*** 封裝并發數和每秒訪問量的橫坐標(yyyy-MM-dd HH:mm:ss)* @param startDate* @param endDate* @return* @throws ParseException*/private static List<String> installCategoryForSeriesLastMin(String startDate,String endDate) throws ParseException {List<String> categoryForSeries = new ArrayList<String>();String[] categoryForSeriesStr = new String[60];SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");Calendar calendar = Calendar.getInstance(); calendar.setTime(sdf.parse(startDate));calendar.add(Calendar.MINUTE, -1);//將startDate的時間設置為上一分鐘for (int i = 0; i < categoryForSeriesStr.length; i++) {categoryForSeriesStr[i]= sdf.format(ApDateTime.getDate(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "" + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE),"yyyy-MM-dd HH:mm"));//yyyy-MM-dd HH:mm//將startDate的時間設置為下一分鐘calendar.add(Calendar.MINUTE, 1);startDate = sdf.format(ApDateTime.getDate( calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "" + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE),"yyyy-MM-dd HH:mm"));//yyyy-MM-dd HH:mm:ss}categoryForSeries.addAll(Arrays.asList(categoryForSeriesStr));System.out.println(" installCategoryForSeriesLastMin categoryForSeries " + categoryForSeries);return categoryForSeries;}/*** 封裝并發數和每秒訪問量的縱坐標* @param startDate* @param endDate* @param list* @param categoryForSeriesLastMin* @param categoryForSeries* @return* @throws ParseException*/private static List<List<EchartsSeries>> installSeries(String startDate,String endDate, List<Map<String, Object>> list,List<String> categoryForSeriesLastMin, List<String> categoryForSeries) throws ParseException {Object[] categoryForSeriesStr = categoryForSeries.toArray();Object[] categoryForSeriesLastMinStr = categoryForSeriesLastMin.toArray();List<EchartsSeries> seriesLeft = new ArrayList<EchartsSeries>();// 縱坐標List<EchartsSeries> seriesRight = new ArrayList<EchartsSeries>();// 縱坐標List<List<EchartsSeries>> series = null;Double[] seriesLeftStr = new Double[categoryForSeriesStr.length];// 左邊縱坐標顯示數據Double[] seriesRightStr = new Double[categoryForSeriesStr.length];// 右邊縱坐標顯示數據Double[] seriesRightStrLastMin = new Double[categoryForSeriesStr.length];SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");// 并發量和每秒訪問量for (int i = 0; i < categoryForSeriesStr.length; i++) { // System.out.println(" list " + list);for (Map<String, Object> superveneData : list) {//獲取與橫坐標刻度對應的小時數據if (categoryForSeriesStr[i].toString().substring(0, 16).equals(sdf.format(sdf.parse(superveneData.get("modify_time").toString())).substring(0, 16))) {//并發量seriesLeftStr[i] = Double.parseDouble(StringUtils.isNotEmpty(superveneData.get("supervene_count").toString()) ? superveneData.get("supervene_count").toString() : "5");//當前橫坐標刻度對應的總訪問量seriesRightStr[i] = Double.parseDouble(StringUtils.isNotEmpty(superveneData.get("total_count").toString()) ? superveneData.get("total_count").toString() : "30000");break;}}}for (int i = 0; i < categoryForSeriesLastMinStr.length; i++) {//獲取當前橫坐標刻度上一分鐘的總訪問量for (Map<String, Object> superveneData : list) {Calendar calendar = Calendar.getInstance(); calendar.setTime(sdf.parse(categoryForSeriesLastMinStr[i].toString()));calendar.add(Calendar.MINUTE, -1);//將categoryStr[i]的時間設置為上一分鐘 // System.out.println("categoryForSeriesLastMinStr[i].toString() " + categoryForSeriesLastMinStr[i].toString() + " superveneData " + sdf.format(sdf.parse(superveneData.get("modify_time").toString())));if (categoryForSeriesLastMinStr[i].toString().substring(0, 16).equals(sdf.format(sdf.parse(superveneData.get("modify_time").toString())).subSequence(0, 16))) {//當前橫坐標刻度對應的上一分鐘的總訪問量seriesRightStrLastMin[i] = Double.parseDouble(StringUtils.isNotEmpty(superveneData.get("total_count").toString()) ? superveneData.get("total_count").toString() : "30000");break;}}//當前橫坐標刻度對應的該分鐘的訪問量seriesRightStr[i] = seriesRightStr[i] - seriesRightStrLastMin[i];}seriesLeft.add(new EchartsSeries("", "", new ArrayList<Double>(Arrays.asList(seriesLeftStr))));seriesRight.add(new EchartsSeries("", "",new ArrayList<Double>(Arrays.asList(seriesRightStr))));series = new ArrayList<List<EchartsSeries>>();series.add(seriesLeft);series.add(seriesRight);return series;} }擴展:
帶時間軸(timeline)的折線圖
(注:以下實現timeline的間隔范圍最大為10,是由options數組內的數據的個數來決定的。)
餅狀圖、柱狀圖和地圖等其他類型的echarts圖表都是類似的道理,這里就不再累述。
總結
以上是生活随笔為你收集整理的【echarts】echarts开发流程详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Spring学习】使用Spring的j
- 下一篇: 智能监控效果图