尚硅谷谷粒学院学习笔记12--统计分析功能,echarts图表显示

1、在service模块下创建子模块

service_statistics

2、application.properties

resources目录下创建文件

# 服务端口
server.port=8008
# 服务名
spring.application.name=service-statistics

# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/gulischool?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

#配置mapper xml文件的路径
mybatis-plus.mapper-locations=classpath:com/atguigu/staservice/mapper/xml/*.xml

#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

3、MP代码生成器生成代码

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.Test;

/**
 * @author
 * @since 2018/12/13
 */
public class CodeGenerator {
    
    

    @Test
    public void run() {
    
    

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir("D:\\ideacode\\guli_parent\\service\\service_statistics" + "/src/main/java");

        gc.setAuthor("dyk");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖

        //UserServie
        gc.setServiceName("%sService");	//去掉Service接口的首字母I

        gc.setIdType(IdType.ASSIGN_ID); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/gulischool?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("staservice"); //模块名
        //包  com.atguigu.eduservice
        pc.setParent("com.atguigu");
        //包  com.atguigu.eduservice.controller
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();

        strategy.setInclude("statistics_daily");

        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);


        // 6、执行
        mpg.execute();
    }
}

4、创建SpringBoot启动类

package com.atguigu.staservice;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@ComponentScan(basePackages = {
    
    "com.atguigu"})
@EnableDiscoveryClient
@EnableFeignClients
@MapperScan("com.atguigu.staservice.mapper")
@EnableScheduling
public class StaApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(StaApplication.class, args);
    }
}

1、在service_ucenter模块创建接口,统计某一天的注册人数

controller

//查询某一天注册人数
    @GetMapping("countRegister/{day}")
    public ResultVo countRegister(@PathVariable String day) {
    
    
        Integer count = memberService.countRegisterDay(day);
        return ResultVo.ok().data("countRegister",count);
    }

service

//查询某一天注册人数
    @Override
    public Integer countRegisterDay(String day) {
    
    
        return baseMapper.countRegisterDay(day);
    }

mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.educenter.mapper.UcenterMemberMapper">
    <!--查询某一天注册人数-->
    <select id="countRegisterDay" resultType="java.lang.Integer">
        SELECT COUNT(*) FROM ucenter_member uc
        WHERE DATE(uc.gmt_create)=#{
    
    day}
    </select>
</mapper>

2、在service_statistics模块创建远程调用接口
创建client包和UcenterClient接口

package com.atguigu.staservice.client;

import com.atguigu.commonutils.ResultVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient("service-ucenter")
public interface UcenterClient {
    
    

    //查询某一天注册人数
    @GetMapping("/educenter/member/countRegister/{day}")
    public ResultVo countRegister(@PathVariable("day") String day);
}

controller

//统计某一天注册人数,生成统计数据
    @PostMapping("registerCount/{day}")
    public ResultVo registerCount(@PathVariable String day) {
    
    
        staService.registerCount(day);
        return ResultVo.ok();
    }

service

@Override
    public void registerCount(String day) {
    
    

        //添加记录之前删除表相同日期的数据
        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.eq("date_calculated",day);
        baseMapper.delete(wrapper);

        //远程调用得到某一天注册人数
        ResultVo registerR = ucenterClient.countRegister(day);
        Integer countRegister = (Integer)registerR.getData().get("countRegister");

        //把获取数据添加数据库,统计分析表里面
        StatisticsDaily sta = new StatisticsDaily();
        sta.setRegisterNum(countRegister); //注册人数
        sta.setDateCalculated(day);//统计日期

        sta.setVideoViewNum(RandomUtils.nextInt(100,200));
        sta.setLoginNum(RandomUtils.nextInt(100,200));
        sta.setCourseNum(RandomUtils.nextInt(100,200));
        baseMapper.insert(sta);
    }

四、添加定时任务

@Component
public class ScheduledTask {
    
    

    @Autowired
    private StatisticsDailyService staService;

    // 0/5 * * * * ?表示每隔5秒执行一次这个方法
    @Scheduled(cron = "0/5 * * * * ?")
    public void task1() {
    
    
        System.out.println("**************task1执行了..");
    }

    //在每天凌晨1点,把前一天数据进行数据查询添加
    @Scheduled(cron = "0 0 1 * * ?")
    public void task2() {
    
    
        staService.registerCount(DateUtil.formatDate(DateUtil.addDays(new Date(), -1)));
    }
}

2、在启动类上添加注解

@EnableScheduling
public class StaApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(StaApplication.class, args);
    }
}

3、在线生成cron表达式
http://cron.qqe2.com/

nginx配置

location ~ /staservice/ {
    
               
    proxy_pass http://localhost:8008;
}

1、创建api

创建src/api/sta.js

import request from '@/utils/request'
export default {
    
    
  // 1 生成统计数据
  createStaData(day) {
    
    
    return request({
    
    
      url: '/staservice/sta/registerCount/' + day,
      method: 'post'
    })
  },
  // 2 获取统计数据
  getDataSta(searchObj) {
    
    
    return request({
    
    
      url: `/staservice/sta/showData/${
    
    searchObj.type}/${
    
    searchObj.begin}/${
    
    searchObj.end}`,
      method: 'get'
    })
  }
}

2、增加路由

src/router/index.js

 {
    
    
    path: '/sta',
    component: Layout,
    redirect: '/sta/create',
    name: '统计分析',
    meta: {
    
     title: '统计分析', icon: 'example' },
    children: [
      {
    
    
        path: 'create',
        name: '生成数据',
        component: () => import('@/views/sta/create'),
        meta: {
    
     title: '生成数据', icon: 'table' }
      },
      {
    
    
        path: 'show',
        name: '图表显示',
        component: () => import('@/views/sta/show'),
        meta: {
    
     title: '图表显示', icon: 'tree' }
      }
    ]
  },

3、创建组件
src/views/statistics/daily/create.vue

<template>
  <div class="app-container">
    <!--表单-->
    <el-form :inline="true" class="demo-form-inline">

      <el-form-item label="日期">
        <el-date-picker
          v-model="day"
          type="date"
          placeholder="选择要统计的日期"
          value-format="yyyy-MM-dd" />
      </el-form-item>

      <el-button
        :disabled="btnDisabled"
        type="primary"
        @click="create()">生成</el-button>
    </el-form>

  </div>
</template>
<script>
import sta from '@/api/sta'
export default {
    
    
  data() {
    
    
    return {
    
    
      day: '',
      btnDisabled: false
    }
  },
  created() {
    
    

  },
  methods: {
    
    
    create() {
    
    
      sta.createStaData(this.day)
        .then(response => {
    
    
          // 提示信息
          this.$message({
    
    
            type: 'success',
            message: '生成数据成功!'
          })
          // 跳转到图表显示页面
          this.$router.push({
    
     path: '/sta/show' })
        })
    }
  }
}
</script>

ECharts简介

ECharts是百度的一个项目,后来百度把Echart捐给apache,用于图表展示,提供了常规的折线图、柱状图、散点图、饼图、K线图,用于统计的盒形图,用于地理数据可视化的地图、热力图、线图,用于关系数据可视化的关系图、treemap、旭日图,多维数据可视化的平行坐标,还有用于 BI 的漏斗图,仪表盘,并且支持图与图之间的混搭。
官方网站:https://echarts.baidu.com/

项目中集成ECharts

1、安装ECharts

npm install --save echarts@4.1.0

2、增加路由
src/router/index.js
在统计分析路由中增加子路由

{
    
    
  path: '/sta',
  component: Layout,
  redirect: '/sta/create',
  name: '统计分析',
  meta: {
    
     title: '统计分析', icon: 'example' },
  children: [
    {
    
    
      path: 'create',
      name: '生成数据',
      component: () => import('@/views/sta/create'),
      meta: {
    
     title: '生成数据', icon: 'table' }
    },
    {
    
    
      path: 'show',
      name: '图表显示',
      component: () => import('@/views/sta/show'),
      meta: {
    
     title: '图表显示', icon: 'tree' }
    }
  ]
},

3、创建组件
src/views/statistics/daily/chart.vue

<template>
  <div class="app-container">
    <!--表单-->
    <el-form :inline="true" class="demo-form-inline">

      <el-form-item>
        <el-select v-model="searchObj.type" clearable placeholder="请选择">
          <el-option label="学员登录数统计" value="login_num"/>
          <el-option label="学员注册数统计" value="register_num"/>
          <el-option label="课程播放数统计" value="video_view_num"/>
          <el-option label="每日课程数统计" value="course_num"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-date-picker
          v-model="searchObj.begin"
          type="date"
          placeholder="选择开始日期"
          value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchObj.end"
          type="date"
          placeholder="选择截止日期"
          value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-button
        :disabled="btnDisabled"
        type="primary"
        icon="el-icon-search"
        @click="showChart()">查询</el-button>
    </el-form>

    <div class="chart-container">
      <div id="chart" class="chart" style="height:500px;width:100%" />
    </div>
  </div>
</template>

三、完成后端业务
1、controller

//图表显示,返回两部分数据,日期json数组,数量json数组
    @GetMapping("showData/{type}/{begin}/{end}")
    public ResultVo showData(@PathVariable String type,@PathVariable String begin,
                      @PathVariable String end) {
    
    
        Map<String,Object> map = staService.getShowData(type,begin,end);
        return ResultVo.ok().data(map);
    }

2、service
接口

Map<String, Object> getShowData(String type, String begin, String end);

实现

//图表显示,返回两部分数据,日期json数组,数量json数组
    @Override
    public Map<String, Object> getShowData(String type, String begin, String end) {
    
    
        //根据条件查询对应数据
        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.between("date_calculated",begin,end);
        wrapper.select("date_calculated",type);
        List<StatisticsDaily> staList = baseMapper.selectList(wrapper);

        //因为返回有两部分数据:日期 和 日期对应数量
        //前端要求数组json结构,对应后端java代码是list集合
        //创建两个list集合,一个日期list,一个数量list
        List<String> date_calculatedList = new ArrayList<>();
        List<Integer> numDataList = new ArrayList<>();

        //遍历查询所有数据list集合,进行封装
        for (int i = 0; i < staList.size(); i++) {
    
    
            StatisticsDaily daily = staList.get(i);
            //封装日期list集合
            date_calculatedList.add(daily.getDateCalculated());
            //封装对应数量
            switch (type) {
    
    
                case "login_num":
                    numDataList.add(daily.getLoginNum());
                    break;
                case "register_num":
                    numDataList.add(daily.getRegisterNum());
                    break;
                case "video_view_num":
                    numDataList.add(daily.getVideoViewNum());
                    break;
                case "course_num":
                    numDataList.add(daily.getCourseNum());
                    break;
                default:
                    break;
            }
        }
        //把封装之后两个list集合放到map集合,进行返回
        Map<String, Object> map = new HashMap<>();
        map.put("date_calculatedList",date_calculatedList);
        map.put("numDataList",numDataList);
        return map;
    }

1、创建api
src/api/statistics/sta.js中添加方法

// 2 获取统计数据
  getDataSta(searchObj) {
    
    
    return request({
    
    
      url: `/staservice/sta/showData/${
    
    searchObj.type}/${
    
    searchObj.begin}/${
    
    searchObj.end}`,
      method: 'get'
    })
  }
<script>
import echarts from 'echarts'
import staApi from '@/api/sta'

export default {
    
    
  data() {
    
    
    return {
    
    
      searchObj: {
    
    },
      btnDisabled: false,
      xData: [],
      yData: []
    }
  },
  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)
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_44866153/article/details/124097580