最终效果
饼状图:饼状图示例,使劲点我!!!
柱状图:柱状图实例,使劲点我!!!
步骤:准备一个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>