谷粒在线教育day16:统计分析功能和添加定时任务

统计分析功能

一、创建微服务

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

service_statistics

2、application.yml

resources目录下创建文件

#服务端口
server:
  port: 8007

#服务名
spring:
  application:
    name: service-statistics
  #服务地址
  cloud:
    nacos:
      discovery:
        #        server-addr: 47.108.14.246:8848
        server-addr: 127.0.0.1:8848
  #返回json的全局时间格式
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

  # mysql数据库连接
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://47.108.14.246:3306/guli?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    username: root
    password: $Panghl0

#mybatis日志
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    auto-mapping-behavior: full
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapper/*/*Mapper.xml
  type-aliases-package: com.atguigu.staservice.entity
#  config-location: classpath:mybatis/mybatis-config.xml

#开启熔断机制
feign:
  hystrix:
    enabled: true
#设置hystrix超时时间 默认1000ms
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000

3、创建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;

/**
 * @Author panghl
 * @Date 2021/2/24 22:08
 * @Description TODO
 **/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@ComponentScan(basePackages = {"com.atguigu"})
@MapperScan("com.atguigu.staservice.mapper")
@EnableScheduling
public class StaApplication {
    public static void main(String[] args) {
        SpringApplication.run(StaApplication.class,args);
    }
}

 

二、实现服务调用

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

controller

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

service

    /**
     * 获取当天注册总人数
     * @param day
     * @return
     */
    @Override
    public Integer countRegister(String day) {
        return baseMapper.selectCountRegister(day);
    }

mapper

package com.atguigu.ucenter.mapper;

import com.atguigu.ucenter.entity.Member;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * <p>
 * 会员表 Mapper 接口
 * </p>
 *
 * @author Panghl
 * @since 2021-02-03
 */
public interface MemberMapper extends BaseMapper<Member> {
    /**
     * 获取当天注册总人数
     * @param day
     * @return
     */
    Integer selectCountRegister(String day);
}
    <!--查询某一天注册人数-->
    <select id="selectCountRegister" resultType="java.lang.Integer">
        select count(1) from ucenter_member uc where DATE(uc.gmt_create) = #{day}
    </select>

 

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

创建client包和UcenterClient接口

package com.atguigu.staservice.client;

import com.atguigu.common.R;
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;

/**
 * @Author panghl
 * @Date 2021/2/24 22:31
 * @Version 1.0
 * @Description TODO
 **/
@FeignClient("service-ucenter")
@Component
public interface UcenterClient {
    @GetMapping("/educenter/member/countRegister/{day}")
    public R countRegister(@PathVariable("day") String day);
}

3、在service_statistics模块调用微服务

controller

package com.atguigu.staservice.controller;


import com.atguigu.common.R;
import com.atguigu.staservice.service.StatisticsDailyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 网站统计日数据 前端控制器
 * </p>
 *
 * @author Panghl
 * @since 2021-02-24
 */
@RestController
@RequestMapping("/staservice/statistics-daily")
@Api(tags = {"统计分析"})
public class StatisticsDailyController {
    @Autowired
    private StatisticsDailyService staService;

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

service

package com.atguigu.staservice.service.impl;

import com.atguigu.common.R;
import com.atguigu.staservice.client.UcenterClient;
import com.atguigu.staservice.entity.StatisticsDaily;
import com.atguigu.staservice.mapper.StatisticsDailyMapper;
import com.atguigu.staservice.service.StatisticsDailyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author Panghl
 * @since 2021-02-24
 */
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {

    @Autowired
    private UcenterClient ucenterClient;
    
    /**
     * 统计某一天的注册人数,生成统计数据
     *
     * @param day
     */
    @Override
    public void registerCount(String day) {

        //添加记录之前删除表相同日期的数据
        deleteDaySame(day);

        R r = ucenterClient.countRegister(day);
        Integer countRegister = (Integer)r.getData().get("countRegister");

        Integer loginNum = RandomUtils.nextInt(100, 200);
        Integer videoViewNum = RandomUtils.nextInt(100, 200);
        Integer courseNum = RandomUtils.nextInt(100, 200);

        //创建统计对象
        StatisticsDaily daily = new StatisticsDaily();
        daily.setRegisterNum(countRegister);
        daily.setDateCalculated(day);
        daily.setLoginNum(loginNum);
        daily.setVideoViewNum(videoViewNum);
        daily.setCourseNum(courseNum);

        baseMapper.insert(daily);
    }

    /**
     * 删除相同日期的数据
     * @param day
     */
    private void deleteDaySame(String day) {
        QueryWrapper<StatisticsDaily> qw = new QueryWrapper<>();
        qw.eq("date_calculated",day);
        baseMapper.delete(qw);
    }
}

 

4、生成数据---前端整合

1、添加路由

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' }
      },
    ]
  },

 

2、创建api

api 目录下创建sta/sta.js文件

import request from "@/utils/request"

export default {
  registerCount(day) {
    return request({
      url: `/staservice/statistics-daily/registerCount/${day}`,
      method: 'post'
    })
  },
}

3、创建组件

src/views/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="createData()"
        >生成</el-button
      >
    </el-form>
  </div>
</template>

<script>
import staApi from "@/api/sta/sta";
export default {
  data() {
    return {
      day: "",
      btnDisabled: false,
    };
  },
  methods: {
    createData() {
      staApi.registerCount(this.day).then((res) => {
        //提示信息
        this.$message({
          type: "success",
          message: "生成数据成功!",
        });
        //跳转到图表显示页面
        this.$router.push({
          path: "/sta/show",
        });
      });
    },
  },
};
</script>

 

2、定时任务

1、在启动类添加注解

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;

/**
 * @Author panghl
 * @Date 2021/2/24 22:08
 * @Description TODO
 **/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@ComponentScan(basePackages = {"com.atguigu"})
@MapperScan("com.atguigu.staservice.mapper")
@EnableScheduling
public class StaApplication {
    public static void main(String[] args) {
        SpringApplication.run(StaApplication.class,args);
    }
}

2、创建定时任务类

package com.atguigu.staservice.scheduled;

import com.atguigu.staservice.service.StatisticsDailyService;
import com.atguigu.staservice.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author panghl
 * @Date 2021/2/25 11:14
 * @Description 每五秒统计注册人数--定时任务
 **/
@Component
public class ScheduledTask {

    @Autowired
    private StatisticsDailyService staService;

    @Scheduled(cron = "0/5 * * * * ? ")
    public void task1() {
        System.out.println("*****------****每五秒执行一次");
    }

    //每天凌晨一点执行
    @Scheduled(cron = "0 0 1 * * ? ")
    public void task2() {
        System.out.println("*****------****获取上一天日期");
        String day = DateUtil.formatDate(DateUtil.addDays(new Date(), -1));
        staService.registerCount(day);
    }

}

 

在线Cron表达式:https://cron.qqe2.com/

查看控制台:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值