最終效果
餅狀圖:
柱狀圖:柱狀圖教程,點我!!!
步驟:準備一個dom——>獲取dom節點——>初始化——>繪製圖表——>渲染數據
html代碼
<template>
<section class="chart-container">
<el-row>
<el-badge class="item" @click.native.prevent="test">
<el-button type="primary" round size="small">告警信息</el-button>
</el-badge>
</el-row>
<el-row>
<el-col :span="11">
<div id="text" style="width:100%; height:200px; margin-top: 150px;">
<span style="font-size:26px">今日告警:56條</span><br/>
<span style="font-size:26px">昨日告警:5條</span><br/>
<span style="font-size:26px">本週告警:266條</span><br/>
<span style="font-size:26px">本月告警:1240條</span><br/>
<span style="font-size:26px">告警數最多的系統:營銷員郵件系統</span><br/>
<span style="font-size:26px">告警數最少的系統:統一身份管理系統</span><br/>
</div>
</el-col>
<el-col :span="12">
<div id="chartColumn" style="width:100%; height:400px;"></div>
</el-col>
<el-col :span="11">
<template>
<el-select v-model="filters.value" placeholder="校驗規則" clearable @change="change" @clear="clear" loading-text="加載中...">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
</el-select>
</template>
<div id="chartLine" style="width:100%; height:400px;"></div>
</el-col>
<el-col :span="12">
<div id="chartPie" style="width:100%; height:400px;"></div>
</el-col>
</el-row>
</section>
</template>
js代碼
<script>
import echarts from 'echarts';
import http from '../../util/http.js';
let code = 1;
let url = {
login: 'http://' + http.host_port + '/login',
columndata: 'http://' + http.host_port + '/columndata',
piedata: 'http://' + http.host_port + '/piedata',
linedata: 'http://' + http.host_port + '/linedata'
}
export default {
data() {
var checkRule_code='';
return {
admin : JSON.parse(sessionStorage.getItem('user')).username,
chartColumn: null,
chartBar: null,
chartLine: null,
chartPie: null,
filters: {
value:''
},
options:[],
value: ''
}
},
//頁面啓動自動加載methods中的方法
created() {
console.log("執行created()函數");
this.getRules();
this.fillColumnChart();
this.fillPieChart();
this.fillLineChart();
},
methods: {
//點擊選擇器清空按鈕時觸發,空單選框選項加載所有數據
clear(){
console.log("清空單選框選項");
this.fillLineChart();
},
//告警信息點擊事件,跳轉校驗結果查詢
test() {
this.$router.push({
path: '/checkresult'
});
},
//當用戶選擇單選框選項時觸發,攜帶選擇的參數,作爲條件去後臺查詢單條數據
change(value){
code++;
this.fillColumnChart();
this.fillPieChart();
//this.fillLineChart();
var chart8 = null;
var div_ = document.getElementById("chartLine");
div_.removeAttribute("_echarts_instance_");
//chart8 = echarts.init(div_);貌似沒啥用
let obj = {};
let para=''; //參數
var label = '';
obj = this.options.find((item)=>{
return item.value === value;
});
console.log("選擇了檢驗規則:"+obj.label);
para={user_id:JSON.parse(sessionStorage.getItem("user")).id,checkRule_code:obj.label};//user_id作爲參數,供後臺判斷用戶所屬信息
this.$post(url.linedata,para)
.then(res => {
if(res != null) {
this.chartLine.setOption({
//工具
toolbox: {
show: true,
feature: {
dataView: { show: false, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
xAxis: {
data: res.category
},
series: res.series
});
} else {
alert("折線圖獲取數據異常!");
}
});
},
//頁面渲染時預加載單選框數據
getRules(){
//this.fillColumnChart();
//this.fillPieChart();
if (sessionStorage.getItem("checkrules")!=null) {
this.options= JSON.parse( sessionStorage.getItem("checkrules"));
console.log("sessionStorage!=null");
}else{
console.log("進入getRules方法,sessionStorage=null");
this.$post('http://'+http.host_port+'/checkRules/getCheckRules',
{user_id:JSON.parse(sessionStorage.getItem("user")).id})
.then((res)=>{
var rules = [];
if (res==null) {
this.$message({
message:'獲取系統選項失敗,請聯繫網站維護人員',
type:'error',
duration:'5000'
});
} else{
rules = res;
var array=[];
for (let i = 0; i < rules.length; i++) {
array.push({label:rules[i],value:i});
};
}
this.options= array;
sessionStorage.setItem('checkrules',JSON.stringify(array));
});
}
},
//繪製柱狀圖
drawColumnChart() {
this.chartColumn = echarts.init(document.getElementById('chartColumn'));
this.chartColumn.setOption({
title: {
text: '各數據庫佔有數據源情況柱狀圖'
},
tooltip: {},
xAxis: {
data: []
},
yAxis: {},
series: [{
name: '',
type: 'bar',
data: []
}]
});
},
//動態渲染柱狀圖
fillColumnChart() {
console.log("動態渲染柱狀圖");
var _this = this;
this.$fetch(url.columndata)
.then(res => {
if(res != null) {
var xaxi = [];
var yaxi = [];
for(var i = 0; i < res.length; i++) {
if(typeof(res[i]) == "string") {
xaxi.push(res[i]);
} else if(typeof(res[i] == "number")) {
yaxi.push(res[i]);
}
}
this.chartColumn.setOption({
//工具
toolbox: {
show: true,
feature: {
dataView: { show: false, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
xAxis: {
data: xaxi,
name: "類型"
},
series: [{
data: yaxi,
type: 'bar',
name: '次數'
}]
});
} else {
alert("柱狀圖數據獲取異常!");
this.$router.push({
path: '/user/list'
});
}
});
},
//繪製折線圖
drawLineChart() {
this.chartLine = echarts.init(document.getElementById('chartLine'));
this.chartLine.setOption({
title: {
text: '規則一週運行趨勢折線圖'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: []
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: []
},
yAxis: {
type: 'value'
},
series: [{
name: '',
type: 'line',
data: []
}]
});
},
//動態渲染折線圖
fillLineChart() {
console.log("動態渲染折線圖");
var _this = this;//實例對象
var user_id; //用戶的user_id
let para=''; //參數
var legend = []; //折線圖的legend
var series = [];
//模擬數據,手寫的json格式數據,供折線圖顯示,後續要從接口接收返回的json
var json = [{name:'反洗錢系統',data:[120, 132, 101, 134, 90, 230, 210]},{name:'大數據管理平臺',data:[538, 512, 123, 452, 433, 321, 254]},
{name:'基礎率分析系統',data:[132, 132, 101, 134, 134, 230, 210]},{name:'統一第三方管理平臺',data:[120, 101, 101, 0, 90, 0, 210]},
{name:'中國人壽電子商務平臺',data:[123, 542, 365, 102, 40, 752, 236]},{name:'國壽e店',data:[240, 111, 365, 241, 850, 243, 111]},
{name:'智能安全監控平臺',data:[235, 655, 444, 0, 111, 333, 666]},{name:'電子商務基礎平臺',data:[254, 653, 258, 236, 42, 0, 123]},
{name:'雲助理',data:[400, 250, 101, 100, 500, 254, 210]},{name:'國壽大健康平臺',data:[666, 132, 101, 0, 90, 230, 210]},
{name:'財務與人力資源管理系統',data:[222, 132, 50, 300, 150, 230, 630]},{name:'生物認證識別系統',data:[225, 132, 101, 134, 60, 200, 0]},
{name:'統一身份管理系統',data:[60, 182, 191, 234, 0, 330, 310]}];
para={user_id:JSON.parse(sessionStorage.getItem("user")).id,checkRule_code:null};//user_id作爲參數,供後臺判斷用戶所屬信息
this.$post(url.linedata,para)
.then(res => {
if(res != null) {
this.chartLine.setOption({
noDataLoadingOption: {
text: '無數據',
effect: 'bubble',
effectOption: {
effect: {
n: 0
}
}
},
//工具
toolbox: {
show: true,
feature: {
dataView: { show: false, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
/* legend: {
data: legend
},*/
xAxis: {
data: res.category
}
,
series: res.series
});
} else {
alert("折線圖獲取數據異常!");
}
});
},
//繪製餅狀圖
drawPieChart() {
this.chartPie = echarts.init(document.getElementById('chartPie'));
this.chartPie.setOption({
title: {
text:'各系統校驗規則數餅狀圖',
x: 'center'
},
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
legend: {
orient: 'vertical',
left: 'left',
data: []
},
series: [{
name: '系統名稱',
type: 'pie',
radius: '70%',
center: ['50%', '60%'],
data: [],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: ' (0, 0, 0, 0.5)'
}
}
}]
});
},
//動態渲染餅狀圖
fillPieChart() {
console.log("動態渲染餅狀圖");
//chartPie.showLoading();等待動畫
//chartPie.hideLoading();
var _this = this;
let para='';
var user_id;
var servicedata=[];
para={user_id:JSON.parse(sessionStorage.getItem("user")).id};
this.$post(url.piedata,para)
.then(res => {
if(res != null) {
for(var i = 0; i < res.name.length; i++) {
var obj=new Object();
obj.name=res.name[i];
obj.value=res.data[i];
servicedata[i]=obj;
}
this.chartPie.setOption({
//工具
toolbox: {
show: true,
feature: {
saveAsImage: { show: true }
}
},
legend: {
data: res.name
},
series: [{
data:servicedata
}]
});
} else {
alert("餅狀圖獲取數據異常!");
}
});
},
drawCharts() {
if(code==1){
this.drawColumnChart()
this.drawLineChart()
this.drawPieChart()
}else{
this.drawLineChart()
}
},
},
mounted: function() {
console.log("執行mounted函數");
this.drawCharts()
},
updated: function() {
if(code==1){
console.log("code="+code+",首次執行updated函數");
}else{
console.log("code="+code+",不是第一次執行updated函數");
this.drawCharts();
}
}
}
</script>
java代碼
/**
* 主頁相關
* @author DSY
*/
@CrossOrigin(origins="*",maxAge=3600) //實現跨域訪問,*可以替換成指定的路徑
@RestController
public class HomeController {
@Autowired
private DataSourceService dataSourceService;
@Autowired
private CheckRuleService checkRuleService;
//主頁柱狀圖獲取數據
@RequestMapping(value = "/columndata", method = RequestMethod.GET)
@ResponseBody
public List columnData() {
//用對象接收返回值,對象存在list裏
List<DataSource> list = dataSourceService.getDbType();
List datalist = new ArrayList<>();
//數據庫類型和出現次數
String dbtype= null;
int count = 0;
//遍歷list拿到每個對象中需要的,dbtype和count
for(int i = 0 ; i < list.size() ; i++) {
dbtype=list.get(i).getDbType();
count = list.get(i).getCount();
datalist.add(dbtype);
datalist.add(count);
}
return datalist;
}
//主頁餅狀圖獲取數據
/*
* 思路
* 把餅狀圖需要的兩組數據(系統名稱和對應的規則數)放在list中,遍歷list存入數組,數組存在map找中,最後轉成json。這樣很麻煩,後續可以改進一下
*
*/
@PostMapping(value = "/piedata")
@ResponseBody
public Object pieData(@RequestBody Map<String,String> para){
List<CheckRule> list = new ArrayList<>();
//JSONArray json = new JSONArray();
//JSONArray json = JSONArray.fromObject(list);
//數據庫中拿到目標數據存在嵌套對象的list中
list = checkRuleService.getPieData(para.get("user_id"));
String[] name= new String[list.size()];
String[] data= new String[list.size()];
Map<String, Object> map = new HashMap<>();
//遍歷list將目標數據分別存在兩個數組中,然後兩個數組作爲元素存在map中,以供後面轉成echart餅狀圖要求的json格式數據
for (int i = 0; i < list.size(); i++) {
name[i] = list.get(i).getApp_name();
data[i] = Integer.toString(list.get(i).getCount());
map.put("name", name);
map.put("data", data);
}
//map轉成json對象返回給頁面
Object json = JSONArray.toJSON(map);
//System.out.println("返回給餅狀圖的json:"+json);
return json;
}
@PostMapping(value = "/linedata")
@ResponseBody
@Test
public Object lineData(@RequestBody Map<String,String> para){
List<CheckRule> list = new ArrayList<CheckRule>();
System.out.println("User_id:"+para.get("user_id"));
System.out.println("checkRule_code:"+para.get("checkRule_code"));
if(para.get("checkRule_code")!=null){
list = checkRuleService.getLineData(para.get("user_id"),para.get("checkRule_code"));
System.out.println("11111111");
}else{
list = checkRuleService.getLineData(para.get("user_id"),null);
System.out.println("222222222");
}
System.out.println("list的長度是:"+list.size());
int intervals = 7;
Integer[] data = new Integer[intervals];
Integer[][] arr = new Integer[list.size()][intervals];
List<String> listtemp = new ArrayList<String>();
ArrayList<String> pastDaysList = new ArrayList<>();
List<String> legend = new ArrayList<String>(); //分組類目
List<String> category = new ArrayList<String>(); //X軸-時間
List<Series> series = new ArrayList<Series>(); //Y軸-數據
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); //定義時間格式,不顯示毫秒
for (int i = 0; i <intervals; i++) {
pastDaysList.add(PastDate.getPastDate(i)); //調用獲取日期的方法,拿到過去七天的日期
}
Collections.reverse(pastDaysList); //反轉數組,日期從小到大排列
category = pastDaysList; //七天日期賦值給echarts參數,作爲X軸時間
for (int i = 0; i < list.size(); i++) {
listtemp.add(df.format(list.get(i).getCreate_time()));
//legend.add(list.get(i).getCheckRule_code());
}
//**********************************************
for (int i = 0; i <list.size(); i++) {
//如果X軸七天中的某一天包含在sql查詢到的時間集合裏,那麼這一時間對應的告警條數添加到data數組中作爲這一天的告警條數,反之當天告警條數爲0
for (int j = 0; j < pastDaysList.size(); j++) {
//if (listtemp.contains(pastDaysList.get(j))) {
if (listtemp.get(i).equals(pastDaysList.get(j))) {
data[j]=list.get(i).getCount();
}else{
data[j]=0;
}
}
System.arraycopy(data, 0, arr[i], 0, 7);
}
for(int a = 0; a<arr.length; a++){
series.add(new Series(list.get(a).getCheckRule_code(), "line",arr[a]));
}
for (int i =0 ; i<legend.size()-1;i++){ //去除重複的規則名
for(int j =i+1; j<legend.size();j++){
if(legend.get(i).equals(legend.get(j))){
legend.remove(i);
}
}
}
Echarts echarts=new Echarts(legend, category, series);
Object json = JSONArray.toJSON(echarts);
System.out.println("返回給折線圖的json:"+json);
return json;
}
}
java的工具類
public class Echarts {
public List<String> legend = new ArrayList<String>();//數據分組
public List<String> category = new ArrayList<String>();//橫座標
public List<Series> series = new ArrayList<Series>();//縱座標
public Echarts(List<String> legendList, List<String> categoryList, List<Series> seriesList) {
super();
this.legend = legendList;
this.category = categoryList;
this.series = seriesList;
}
}
/**
* 主頁相關
* 供主頁折線圖渲染數據的參數
* @author DSY
*/
public class Series {
public String name;
public String type;
public Integer[] data;
public Series( String name, String type, Integer[] data) {
super();
this.name = name;
this.type = type;
this.data = data;
}
}
SQL語句
<!-- 通過用戶ID查詢所有校驗規則對應的告警數,供主頁折線圖展示 -->
<select id="getLineData" resultType="checkRule">
SELECT result.alert_sum as count,checkrule.checkRule_code as checkRule_code,result.create_time as create_time
FROM tb_tasks task
LEFT JOIN tb_checkresults result on task.task_id = result.task_id
LEFT JOIN tb_checkrules checkrule on task.checkRule_code = checkrule.checkRule_code
LEFT JOIN system_app app on app.id = checkrule.app_id
where <if test="_parameter!=null">user_id=#{user_id} and</if>
<if test="checkRule_code!=null">checkrule.checkRule_code=#{checkRule_code} and</if>
<![CDATA[ DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= date(result.create_time)]]>
GROUP BY result.create_time
ORDER BY result.create_time ASC
</select>