官方網站:https://echarts.apache.org/examples/zh/index.html
一、前端
0.安裝echarts
npm install echarts --save
1.編寫html
用來顯示圖表
<div class="chart-container">
<div id="chart" class="chart" style="height:500px;width:100%" />
</div>
觸發顯示圖標的按鈕
<el-button
:disabled="btnDisabled"
type="primary"
icon="el-icon-search"
@click="showChart()">查詢</el-button>
2.引入echart
四版本
import echarts from 'echarts'
五版本
import * as echarts from 'echarts'
3.編寫調用方法
編寫方法getDataSta(),用來獲取后端數據
//用來獲取后端數據
getDataSta(searchObj) {
return request({
url: `/staservice/sta/showData/${searchObj.type}/${searchObj.begin}/${searchObj.end}`,
method: 'get'
})
}
4.編寫js
showChart():用來獲取后端傳來的數據
其中格式必須為json數組格式
setChart()固定寫法
一般只修改x,y軸數據就可以
methods:{
showChart() {
staApi.getDataSta(this.searchObj)
.then(response => {
console.log('*****************'+response)
this.yData = response.data.numDataList
this.xData = response.data.date_calculatedList
//調用下面生成圖表的方法,改變值
this.setChart()
})
},
setChart() {
// 基於准備好的dom,初始化echarts實例
this.chart = echarts.init(document.getElementById('chart'))
// console.log(this.chart)
// 指定圖表的配置項和數據
var option = {
title: {
text: '數據統計'
},
tooltip: {
trigger: 'axis'
},
dataZoom: [{
show: true,
height: 30,
xAxisIndex: [
0
],
bottom: 30,
start: 10,
end: 80,
handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
handleSize: '110%',
handleStyle: {
color: '#d3dee5'
},
textStyle: {
color: '#fff'
},
borderColor: '#90979c'
},
{
type: 'inside',
show: true,
height: 15,
start: 1,
end: 35
}],
// x軸是類目軸(離散數據),必須通過data設置類目數據
xAxis: {
type: 'category',
data: this.xData
},
// y軸是數據軸(連續數據)
yAxis: {
type: 'value'
},
// 系列列表。每個系列通過 type 決定自己的圖表類型
series: [{
// 系列中的數據內容數組
data: this.yData,
// 折線圖
type: 'line'
}]
}
this.chart.setOption(option)
}
}
二、后端
1.控制層接受前端數據
/**
* 圖表顯示,返回日期和數量數組
* @param begin 開始日期
* @param end 結束日期
* @param type 查詢類型
* @return
*/
@ApiOperation("圖表顯示,返回日期和數量數組")
@GetMapping("showData/{type}/{begin}/{end}")
public Result showData(@PathVariable String type,
@PathVariable String begin,
@PathVariable String end){
Map<String,Object> map = statisticsDailyService.getData(type,begin,end);
return Result.ok().data(map);
}
2.實現類的方法
獲取數據庫中的數據,
將結果封裝在兩個list中
日期list
數量list
/**
* 獲取統計數據
* @param type 查詢類型(注冊、播放數量等)
* @param begin 開始時間
* @param end 結束時間
* @return map
*/
@Override
public Map<String, Object> getData(String type, String begin, String end) {
QueryWrapper<StatisticsDaily> queryWrapper = new QueryWrapper<>();
//篩選日期
queryWrapper.between("date_calculated",begin,end);
//精准查詢日期和選擇的類型
queryWrapper.select("date_calculated",type);
List<StatisticsDaily> statisticsDailies = baseMapper.selectList(queryWrapper);
//將結果封裝在兩個list中
//日期list
List<String> dateCalculatedList = new ArrayList<>();
//數量list
List<Integer> countList = new ArrayList<>();
for (StatisticsDaily daily : statisticsDailies) {
dateCalculatedList.add(daily.getDateCalculated());
switch (type) {
case "login_num":
countList.add(daily.getLoginNum());
break;
case "register_num":
countList.add(daily.getRegisterNum());
break;
case "video_view_num":
countList.add(daily.getVideoViewNum());
break;
case "course_num":
countList.add(daily.getCourseNum());
break;
default:
break;
}
}
HashMap<String, Object> map = new HashMap<>();
map.put("date_calculatedList",dateCalculatedList);
map.put("numDataList",countList);
return map;
}
三、數據庫
1.建表語句
CREATE TABLE `statistics_daily` ( `id` char(19) NOT NULL COMMENT '主鍵', `date_calculated` varchar(20) NOT NULL COMMENT '統計日期', `register_num` int(11) NOT NULL DEFAULT '0' COMMENT '注冊人數', `login_num` int(11) NOT NULL DEFAULT '0' COMMENT '登錄人數', `video_view_num` int(11) NOT NULL DEFAULT '0' COMMENT '每日播放視頻數', `course_num` int(11) NOT NULL DEFAULT '0' COMMENT '每日新增課程數', `gmt_create` datetime NOT NULL COMMENT '創建時間', `gmt_modified` datetime NOT NULL COMMENT '更新時間', PRIMARY KEY (`id`), KEY `statistics_day` (`date_calculated`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='網站統計日數據';
2.記錄來源
方法一:在控制層有可以主動調用的接口來查詢注冊人數等數據信息
方法二:在定時任務中可以每天定時調用service的方法來統計
定時任務
@Componentpublic class ScheduleTask { @Autowired private StatisticsDailyService statisticsDailyService; /** * 定時任務 * 每天凌晨1點自動查詢前一天的統計數據 */ @Scheduled(cron = "0 0 1 * * ?") public void updateStatisticsInfo() { //計算前一天日期 String preDay = DateUtil.formatDate(DateUtil.addDays(new Date(),-1)); statisticsDailyService.countRegister(preDay); }}
統計方法
/**
* 統計人數
* @param day 日期
*/
@Transactional(rollbackFor = Exception.class)
@Override
public void countRegister(String day) {
//防止重復添加,先刪除
baseMapper.delete(new QueryWrapper<StatisticsDaily>().eq("date_calculated",day));
Result result = ucenterClient.countRegister(day);
int countRegister = (int)result.getData().get("countRegister");
StatisticsDaily statisticsDaily = new StatisticsDaily();
//賦值統計的數據
statisticsDaily.setRegisterNum(countRegister);
statisticsDaily.setDateCalculated(day);
// TODO 隨機數改為真實數據
statisticsDaily.setVideoViewNum( RandomUtils.nextInt(100,200));
statisticsDaily.setLoginNum(RandomUtils.nextInt(100,200));
statisticsDaily.setCourseNum(RandomUtils.nextInt(100,200));
//添加到數據庫中
baseMapper.insert(statisticsDaily);
}
四、實體數據
@TableField(fill = FieldFill.INSERT_UPDATE)注解 需要配置類
package com.gyb.staservice.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 網站統計日數據
* </p>
*
* @author 郜宇博
* @since 2021-10-27
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="StatisticsDaily對象", description="網站統計日數據")
public class StatisticsDaily implements Serializable {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主鍵")
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@ApiModelProperty(value = "統計日期")
private String dateCalculated;
@ApiModelProperty(value = "注冊人數")
private Integer registerNum;
@ApiModelProperty(value = "登錄人數")
private Integer loginNum;
@ApiModelProperty(value = "每日播放視頻數")
private Integer videoViewNum;
@ApiModelProperty(value = "每日新增課程數")
private Integer courseNum;
@ApiModelProperty(value = "創建時間")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新時間")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
}