码迷,mamicode.com
首页 > 其他好文 > 详细

45.系统后台--统计分析

时间:2021-04-22 15:21:22      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:时间格式   chart   path   utf8   配置   bre   成功   wchar   random   

技术图片

 

 

 目标:对学员登录数、学员注册数、课程播放数、每日课程数进行特定日期统计。画出上图。

一、数据库设计

statistics_daily

技术图片
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=网站统计日数据;
View Code

二、统计分析【后端】

1、创建微服务

1.1、在service模块下创建子模块service_statistics

1.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/guli?characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123

#返回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

#开启熔断机制
feign.hystrix.enabled=true
# 设置hystrix超时时间,默认1000ms
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=3000
View Code

1.3、MP代码生成器生成代码

1.4、创建SpringBoot启动类

技术图片
@SpringBootApplication
@MapperScan("com.atguigu.staservice.mapper")
@ComponentScan("com.atguigu")
@EnableDiscoveryClient
@EnableFeignClients
@EnableScheduling
public class StaApplication {
    public static void main(String[] args) {
        SpringApplication.run(StaApplication.class, args);
    }
}
View Code

@EnableScheduling为定时任务类组件

2、实现服务调用

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

controller

 

技术图片
    //查询某一天注册人数
    @ApiOperation(value = "查询某一天注册人数")
    @GetMapping("countRegister/{day}")
    public R countRegister(@PathVariable String day){
        Integer count =  memberService.countRegisterDay(day);
        return R.ok().data("countRegister",count);
    }
View Code

service

 

技术图片
Integer countRegisterDay(String day);
View Code

 

serviceImpl

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

mapper

技术图片
public interface UcenterMemberMapper extends BaseMapper<UcenterMember> {
    Integer countRegisterDay(@Param("value") String day);
}
View Code

mapper.xml

技术图片
    <!-- //查询某一天注册人数   -->
    <select id="countRegisterDay" resultType="java.lang.Integer">
        SELECT COUNT(*)
        FROM ucenter_member
        WHERE DATE(gmt_create) = #{value}
    </select>
View Code

2.2、在service_statistics模块创建远程调用接口

创建client包和UcenterClient接口
技术图片
@Component
@FeignClient("service-ucenter")
public interface UcenterClient {
    @GetMapping("/educenter/member/countRegister/{day}")
    public R countRegister(@PathVariable("day") String day);
}
View Code

2.3、在service_statistics模块调用微服务

两个接口:

registerCount  1、对数据库中学员登录数、学员注册数、课程播放数、每日课程数进行某天统计,插入到statistics_daily中

getShowData  2、图表显示,返回两部分数据,日期json数组,数量json数组

controller   

技术图片
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {

    @Autowired
    private UcenterClient ucenterClient;

    @Override
    public void registerCount(String day) {

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

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

        //获取统计信息
        Integer loginNum = RandomUtils.nextInt(100, 200);//TODO
        Integer videoViewNum = RandomUtils.nextInt(100, 200);//TODO
        Integer courseNum = RandomUtils.nextInt(100, 200);//TODO

        //创建统计对象
        StatisticsDaily daily = new StatisticsDaily();
        daily.setRegisterNum(registerNum);//注册人数
        daily.setLoginNum(loginNum);
        daily.setVideoViewNum(videoViewNum);
        daily.setCourseNum(courseNum);
        daily.setDateCalculated(day);//统计日期
        //把获取数据添加到数据库
        baseMapper.insert(daily);
    }

    //图表显示,返回两部分数据,日期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<String> data_calculatedList = new ArrayList<>();
        List<Integer> numDataList = new ArrayList<>();
        
        //遍历查询所有数据list集合,进行封装
        for (int i = 0; i < stalist.size(); i++) {
            StatisticsDaily daily = stalist.get(i);
            //封装日期list集合
            data_calculatedList.add(daily.getDateCalculated());
            //封装对应数量
            switch (type){
                case "login_num":
                    numDataList.add(daily.getLoginNum());
                    break;
                case "video_view_num":
                    numDataList.add(daily.getVideoViewNum());
                    break;
                case "course_num":
                    numDataList.add(daily.getCourseNum());
                    break;
                case "register_num":
                    numDataList.add(daily.getRegisterNum());
                    break;
            }
        }
        //把封装之后的list集合放到map集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("data_calculatedList",data_calculatedList);
        map.put("numDataList",numDataList);
        return map;
    }
}
View Code
service
技术图片
public interface StatisticsDailyService extends IService<StatisticsDaily> {

    void registerCount(String day);

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

serviceImpl

技术图片
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {

    @Autowired
    private UcenterClient ucenterClient;

    @Override
    public void registerCount(String day) {

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

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

        //获取统计信息
        Integer loginNum = RandomUtils.nextInt(100, 200);//TODO
        Integer videoViewNum = RandomUtils.nextInt(100, 200);//TODO
        Integer courseNum = RandomUtils.nextInt(100, 200);//TODO

        //创建统计对象
        StatisticsDaily daily = new StatisticsDaily();
        daily.setRegisterNum(registerNum);//注册人数
        daily.setLoginNum(loginNum);
        daily.setVideoViewNum(videoViewNum);
        daily.setCourseNum(courseNum);
        daily.setDateCalculated(day);//统计日期
        //把获取数据添加到数据库
        baseMapper.insert(daily);
    }

    //图表显示,返回两部分数据,日期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<String> data_calculatedList = new ArrayList<>();
        List<Integer> numDataList = new ArrayList<>();
        
        //遍历查询所有数据list集合,进行封装
        for (int i = 0; i < stalist.size(); i++) {
            StatisticsDaily daily = stalist.get(i);
            //封装日期list集合
            data_calculatedList.add(daily.getDateCalculated());
            //封装对应数量
            switch (type){
                case "login_num":
                    numDataList.add(daily.getLoginNum());
                    break;
                case "video_view_num":
                    numDataList.add(daily.getVideoViewNum());
                    break;
                case "course_num":
                    numDataList.add(daily.getCourseNum());
                    break;
                case "register_num":
                    numDataList.add(daily.getRegisterNum());
                    break;
            }
        }
        //把封装之后的list集合放到map集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("data_calculatedList",data_calculatedList);
        map.put("numDataList",numDataList);
        return map;
    }
}
View Code

3、添加定时任务

3.1、创建定时任务类,使用cron表达式

复制日期工具类
技术图片
@Component
public class ScheduledTask {

    @Autowired
    private StatisticsDailyService dailyService;

    /**
     * 测试
     * 每天七点到二十三点每五秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void task1() {
        System.out.println("*********++++++++++++*****执行了");
    }

    /**
     * 每天凌晨1点执行定时
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void task2() {
        //获取上一天的日期
        String day = DateUtil.formatDate(DateUtil.addDays(new Date(), -1));
        dailyService.createStatisticsByDay(day);

    }
}
View Code

3.2、在启动类上添加注解@EnableScheduling

 

3.3、在线生成cron表达式

 

http://cron.qqe2.com/

二、统计分析【前端】

1、nginx配置

技术图片
location ~ /staservice/ {           
    proxy_pass http://localhost:8008;
}
View Code

2、前端页面实现

2.1、创建api

创建src/api/sta.js
技术图片
import request from ‘@/utils/request‘

export default {

  //1 生成统计数据
  createStatistics(day) {
    return request({
      url: `/staservice/sta/registerCount/${day}`,
      method: ‘post‘
    })
  },
  //2 获取统计数据
  showChart(searchObj) {
    return request({
        url: `/staservice/sta/showData/${searchObj.type}/${searchObj.begin}/${searchObj.end}`,
        method: ‘get‘
    })
}
}
View Code

2、增加路由

src/router/index.js
技术图片
{
    path: ‘/sta‘,
    component: Layout,
    redirect: ‘/sta/table‘,
    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‘ }
      }
    ]
  }
View Code

3、创建组件

src/views/statistics/sta/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 daily from ‘@/api/sta‘

export default {
  data() {
    return {
      day: ‘‘,
      btnDisabled: false
    }
  },

  methods: {
    create() {
      this.btnDisabled = true
      daily.createStatistics(this.day).then(response => {
        this.btnDisabled = false
        this.$message({
          type: ‘success‘,
          message: ‘生成数据成功‘
        })
        this.$router.push({path:‘/sta/show‘})
      })
    }
  }
}
</script>
View Code

src/views/statistics/sta/show.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>
<script>
import echarts from ‘echarts‘
import staApi from ‘@/api/sta‘

export default {
  data() {
    return {
      searchObj: {
        type: ‘‘,
        begin: ‘‘,
        end: ‘‘
      },
      btnDisabled: false,
      chart: null,
      title: ‘‘,
      xData: [],
      yData: []
    }
  },
  methods: {
    showChart() {
        this.initChartData()
        // this.setChart()//放在initChartData回调中执行
        },

        // 准备图表数据
    initChartData() {
        staApi.showChart(this.searchObj).then(response => {
            // 数据
            this.yData = response.data.numDataList

            // 横轴时间
            this.xData = response.data.data_calculatedList

            // 当前统计类别
            switch (this.searchObj.type) {
            case ‘register_num‘:
                this.title = ‘学员注册数统计‘
                break
            case ‘login_num‘:
                this.title = ‘学员登录数统计‘
                break
            case ‘video_view_num‘:
                this.title = ‘课程播放数统计‘
                break
            case ‘course_num‘:
                this.title = ‘每日课程数统计‘
                break
            }

            this.setChart()
        })
    },

    // 设置图标参数
    setChart() {
      // 基于准备好的dom,初始化echarts实例
      this.chart = echarts.init(document.getElementById(‘chart‘))
      // console.log(this.chart)

      // 指定图表的配置项和数据
      var option = {
        // x轴是类目轴(离散数据),必须通过data设置类目数据
        xAxis: {
          type: ‘category‘,
          data: this.xData
        },
        // y轴是数据轴(连续数据)
        yAxis: {
          type: ‘value‘
        },
        title: {
            text: this.title
        },
        tooltip: {
            trigger: ‘axis‘
        },
        // 系列列表。每个系列通过 type 决定自己的图表类型
        series: [{
          // 系列中的数据内容数组
          data: this.yData,
          // 折线图
          type: ‘line‘
        }],
        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
            }]
        }

        this.chart.setOption(option)
    }
  }
}
</script>
View Code

 

 

45.系统后台--统计分析

标签:时间格式   chart   path   utf8   配置   bre   成功   wchar   random   

原文地址:https://www.cnblogs.com/ldh-up/p/14683257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!