Day215.课程详细页面功能完善、Echarts统计分析模块[生成统计数据+生成图表]前后端整合 -谷粒学院
谷粒學(xué)院
課程詳細(xì)頁面功能完善
一、修改課程詳細(xì)接口
1、在service_order模塊添加接口
用于判斷訂單中status值是否為1,為1則為已支付
@RestController @CrossOrigin @RequestMapping("/eduorder/t-order") public class TOrderController {@Autowiredprivate TOrderService tOrderService;.........//根據(jù)【用戶id、課程id】查詢訂單表中的狀態(tài)@GetMapping("/isBuyCourse/{memberId}/{courseId}")public Boolean isBuyCourse(@PathVariable String memberId,@PathVariable String courseId) {QueryWrapper<TOrder> wrapper = new QueryWrapper<>();wrapper.eq("course_id",courseId);wrapper.eq("member_id",memberId);wrapper.eq("status",1);//支付狀態(tài) 【1】代表已支付int result = tOrderService.count(wrapper);if (result>0){//已支付return true;}else {return false;}}}2、在service_edu模塊課程詳情接口遠(yuǎn)程調(diào)用
(1)創(chuàng)建OrderClient接口
- com.achang.eduservice.client.OrderClient
確保加入nacos注冊中心配置文件,且在主配置類標(biāo)注@EnableFeignClients
@Component @FeignClient(value = "service-order",fallback = OrderClientImpl.class) public interface OrderClient {//根據(jù)【用戶id、課程id】查詢訂單表中的狀態(tài)@GetMapping("/eduorder/t-order/isBuyCourse/{memberId}/{courseId}")public Boolean isBuyCourse(@PathVariable("memberId") String memberId, @PathVariable("courseId") String courseId);}- OrderClientImpl
兜底方法
@Component public class OrderClientImpl implements OrderClient {@Overridepublic Boolean isBuyCourse(String memberId, String courseId) {return null;} }(2)修改之前的課程詳情接口調(diào)用
- com.achang.eduservice.controller.front.CourseFrontController
二、修改課程詳情頁面
三、測試
統(tǒng)計分析功能(生成統(tǒng)計數(shù)據(jù))
0、需求分析
一、數(shù)據(jù)庫設(shè)計
1、數(shù)據(jù)庫
guli_statistics
2、數(shù)據(jù)表
# # Structure for table "statistics_daily" #CREATE TABLE `statistics_daily` (`id` char(19) NOT NULL COMMENT '主鍵',`date_calculated` varchar(20) NOT NULL COMMENT '統(tǒng)計日期',`register_num` int(11) NOT NULL DEFAULT '0' COMMENT '注冊人數(shù)',`login_num` int(11) NOT NULL DEFAULT '0' COMMENT '登錄人數(shù)',`video_view_num` int(11) NOT NULL DEFAULT '0' COMMENT '每日播放視頻數(shù)',`course_num` int(11) NOT NULL DEFAULT '0' COMMENT '每日新增課程數(shù)',`gmt_create` datetime NOT NULL COMMENT '創(chuàng)建時間',`gmt_modified` datetime NOT NULL COMMENT '更新時間',PRIMARY KEY (`id`),KEY `statistics_day` (`date_calculated`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='網(wǎng)站統(tǒng)計日數(shù)據(jù)';# # Data for table "statistics_daily" #二、創(chuàng)建微服務(wù)
1、在service模塊下創(chuàng)建子模塊
service_statistics
2、application.properties
resources目錄下創(chuàng)建文件
# 服務(wù)端口 server.port=8008# 服務(wù)名 spring.application.name=service-statistics# mysql數(shù)據(jù)庫連接 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=00000# 返回json的全局格式 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8# 配置mybatis xml文件的路徑 mybatis-plus.mapper-locations=classpath:com.achang.staservice.mapper.xml/*.xml# mybatis日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl# nacos服務(wù)地址 spring.cloud.nacos.discovery.server-addr=localhost:8848# 開啟熔斷機(jī)制 feign.hystrix.enabled=true# 設(shè)置hystrix超時時間,默認(rèn)1000ms hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=30003、MP代碼生成器生成代碼
@Test public void run(){// 1、創(chuàng)建代碼生成器AutoGenerator mpg = new AutoGenerator();// 2、全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir("D:\\JavaStudy\\gulixueyuan\\guli_parent\\service\\service_statistics" + "/src/main/java"); //輸出目錄gc.setAuthor("achang"); //作者名gc.setOpen(false); //生成后是否打開資源管理器gc.setFileOverride(false); //重新生成時文件是否覆蓋gc.setServiceName("%sService"); //去掉Service接口的首字母Igc.setIdType(IdType.ID_WORKER_STR); //主鍵策略gc.setDateType(DateType.ONLY_DATE);//定義生成的實體類中日期類型gc.setSwagger2(true);//開啟Swagger2模式mpg.setGlobalConfig(gc);// 3、數(shù)據(jù)源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("00000");dsc.setDbType(DbType.MYSQL);mpg.setDataSource(dsc);// 4、包配置PackageConfig pc = new PackageConfig();//生成包:com.achang.eduservicepc.setModuleName("staservice"); //模塊名pc.setParent("com.achang");//生成包:com.achang.oss.controllerpc.setController("controller");pc.setEntity("entity");pc.setService("service");pc.setMapper("mapper");mpg.setPackageInfo(pc);// 5、策略配置StrategyConfig strategy = new StrategyConfig();strategy.setInclude("statistics_daily");//根據(jù)數(shù)據(jù)庫哪張表生成,有多張表就加逗號繼續(xù)填寫strategy.setNaming(NamingStrategy.underline_to_camel);//數(shù)據(jù)庫表映射到實體的命名策略strategy.setTablePrefix("statistics" + "_"); //生成實體時去掉表前綴strategy.setColumnNaming(NamingStrategy.underline_to_camel);//數(shù)據(jù)庫表字段映射到實體的命名策略strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter鏈?zhǔn)讲僮?/span>strategy.setRestControllerStyle(true); //restful api風(fēng)格控制器strategy.setControllerMappingHyphenStyle(true); //url中駝峰轉(zhuǎn)連字符mpg.setStrategy(strategy);// 6、執(zhí)行mpg.execute();}4、創(chuàng)建SpringBoot啟動類
@SpringBootApplication @EnableFeignClients @MapperScan("com.achang.staservice.mapper") @EnableDiscoveryClient //開啟服務(wù)發(fā)現(xiàn) @ComponentScan("com.achang") public class staserviceMain8008 {public static void main(String[] args) {SpringApplication.run(staserviceMain8008.class,args);} }三、實現(xiàn)服務(wù)調(diào)用
1、在service_ucenter模塊創(chuàng)建接口,統(tǒng)計某一天的注冊人數(shù)
- controller
- service
接口
public interface UcenterMemberService extends IService<UcenterMember> {...........//根據(jù)日期,獲取那天注冊人數(shù)Integer getCountRegister(String day); }impl
@Service public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {@Autowiredprivate RedisTemplate<String,String> redisTemplate;...........//根據(jù)日期,獲取那天注冊人數(shù)@Overridepublic Integer getCountRegister(String day) {return baseMapper.getCountRegister(day);}}- mapper
接口
public interface UcenterMemberMapper extends BaseMapper<UcenterMember> {Integer getCountRegister(String day); }xml
<select id="getCountRegister" resultType="java.lang.Integer">select count(1)from ucenter_memberwhere date(gmt_create) = #{day} </select>?
2、在service_statistics模塊創(chuàng)建遠(yuǎn)程調(diào)用接口
創(chuàng)建client包和UcenterClient接口和impl
- 接口
- impl
兜底方法
@Component public class UcenterClientImpl implements UcenterClient {@Overridepublic R countRegister(String day) {return null;} }3、在service_statistics模塊調(diào)用微服務(wù)
- controller
- service
impl
@Service public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {@Autowiredprivate UcenterClient ucenterClient;//統(tǒng)計某一天注冊人數(shù)@Overridepublic void createStatisticsByDay(String day) {//添加之前先刪除表相同的數(shù)據(jù)QueryWrapper<Daily> wrapper = new QueryWrapper<>();wrapper.eq("date_calculated",day);baseMapper.delete(wrapper);//遠(yuǎn)程調(diào)用得到某一天的注冊人數(shù)R registerR = ucenterClient.countRegister(day);Integer countRegister = (Integer) registerR.getData().get("countRegister");//其他的數(shù)據(jù)類似,也是通過遠(yuǎn)程調(diào)用,獲取數(shù)據(jù)返回即可,下面使用隨機(jī)數(shù)模擬//把獲取到的數(shù)據(jù)Daily daily = new Daily();daily.setRegisterNum(countRegister);//注冊人數(shù)daily.setCourseNum(RandomUtils.nextInt(100,200));daily.setLoginNum(RandomUtils.nextInt(200,300));//登錄數(shù)daily.setVideoViewNum(RandomUtils.nextInt(200,300));//視頻流量數(shù)daily.setDateCalculated(day);//統(tǒng)計日期//添加到數(shù)據(jù)庫中baseMapper.insert(daily);}}接口
public interface DailyService extends IService<Daily> {//統(tǒng)計某一天注冊人數(shù)void createStatisticsByDay(String day); }- 測試,啟動兩個訪問
訪問:localhost:8008/swagger-ui.html
- 記住給實體類添加
- 配置nginx
測試成功
四、添加定時任務(wù)
在特定的時間,讓程序自動執(zhí)行,鬧鐘一樣
七子表達(dá)式,總共有7位,但是springboot整合只整合了前面6位,最后一位的年沒有整合,直接默認(rèn)是每年
1、在啟動類上添加注解
@EnableScheduling 開啟定時任務(wù)
2、創(chuàng)建定時任務(wù)類,使用cron表達(dá)式
com.achang.staservice.schedule.ScheduledTask
@Component public class ScheduledTask {//(0/5 * * * * ?):每隔5秒執(zhí)行一次@Scheduled(cron = "0/5 * * * * ?")//指定cron表達(dá)式規(guī)則public void task01(){System.out.println("=========我執(zhí)行了");} }- 通過工具類,在每天凌晨1點執(zhí)行方法,把前一天的數(shù)據(jù)查詢進(jìn)行添加
3、在線生成cron表達(dá)式
網(wǎng)上一大堆,隨便找
http://cron.qqe2.com/
統(tǒng)計數(shù)據(jù)前端整合
一、前端頁面實現(xiàn)
1、添加路由
guli-admin\src\router\index.js
//統(tǒng)計分析{path: '/sta',component: Layout,redirect: '/sta/create',name: '統(tǒng)計分析',meta: { title: '統(tǒng)計分析', icon: 'nested' },children: [{path: 'create',name: '生成數(shù)據(jù)',component: () => import('@/views/sta/create.vue'),meta: { title: '生成數(shù)據(jù)', icon: 'table' }},{path: 'show',name: '圖表顯示',component: () => import('@/views/sta/show.vue'),meta: { title: '圖表顯示', icon: 'nested' }}]},2、創(chuàng)建api
import request from '@/utils/request' //引入已經(jīng)封裝好的axios 和 攔截器export default{//生成統(tǒng)計數(shù)據(jù)createStaByDay(day){return request({url:'/staservice/daily/createStatisticsByDay/'+day,method: 'post'})}}3、創(chuàng)建組件
guli-admin\src\views\sta\create.vue
- create
html頁面
<template><div class="app-container"><!--表單--><el-form :inline="true" class="demo-form-inline"><el-form-item label="日期"><el-date-pickerv-model="day"type="date"placeholder="選擇要統(tǒng)計的日期"value-format="yyyy-MM-dd"/></el-form-item><el-button :disabled="btnDisabled" type="primary" @click="create()">生成</el-button></el-form></div> </template>js腳本
<script> import staApi from "@/api/sta"; export default {data() {return {day: "",btnDisabled: false,};},created() {},methods: {create() {staApi.createStaByDay(this.day).then((resp) => {//提示this.$message({type: "success",message: "生成成功!",});//跳轉(zhuǎn)頁面到showthis.$router.push({path:'/sta/show'})});},}, }; </script>- 效果
測試成功
統(tǒng)計數(shù)據(jù)圖表顯示ECharts
一、ECharts
1、簡介
ECharts是百度的一個項目,后來百度把Echart捐給apache,用于圖表展示,提供了常規(guī)的折線圖、柱狀圖、散點圖、餅圖、K線圖,用于統(tǒng)計的盒形圖,用于地理數(shù)據(jù)可視化的地圖、熱力圖、線圖,用于關(guān)系數(shù)據(jù)可視化的關(guān)系圖、treemap、旭日圖,多維數(shù)據(jù)可視化的平行坐標(biāo),還有用于 BI 的漏斗圖,儀表盤,并且支持圖與圖之間的混搭。
官方網(wǎng)站:https://echarts.baidu.com/
2、基本使用
入門參考:官網(wǎng)->文檔->教程->5分鐘上手ECharts
(1)創(chuàng)建html頁面:柱圖.html
(2)引入ECharts
<!-- 引入 ECharts 文件 --> <script src="echarts.min.js"></script>(3)定義圖表區(qū)域
<!-- 為ECharts準(zhǔn)備一個具備大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div>(4)渲染圖表
<script type="text/javascript"> // 基于準(zhǔn)備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById("main")); // 指定圖表的配置項和數(shù)據(jù) var option = {title: {text: "ECharts 入門示例",},tooltip: {},legend: {data: ["銷量"],},xAxis: {data: ["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"],},yAxis: {},series: [{name: "銷量",type: "bar",data: [5, 20, 36, 10, 10, 20],},], }; // 使用剛指定的配置項和數(shù)據(jù)顯示圖表。 myChart.setOption(option); </script>3、折線圖
實例參考:官網(wǎng)->實例->官方實例 https://echarts.baidu.com/examples/
折線圖.html
<script> var myChart = echarts.init(document.getElementById("main")); var option = {//x軸是類目軸(離散數(shù)據(jù)),必須通過data設(shè)置類目數(shù)據(jù)xAxis: {type: "category",data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],},//y軸是數(shù)據(jù)軸(連續(xù)數(shù)據(jù))yAxis: {type: "value",},//系列列表。每個系列通過 type 決定自己的圖表類型series: [{//系列中的數(shù)據(jù)內(nèi)容數(shù)組data: [820, 932, 901, 934, 1290, 1330, 1320],//折線圖type: "line",},], }; myChart.setOption(option); </script>二、項目中集成ECharts
1、安裝ECharts
npm install --save echarts@4.1.02、路由
src/router/index.js
在統(tǒng)計分析路由中增加子路由
3、創(chuàng)建組件
guli-admin\src\views\sta\show.vue
- 模板
- js:暫時顯示臨時數(shù)據(jù)
三、完成后端業(yè)務(wù)
1、controller
@RestController @RequestMapping("/staservice/daily") @CrossOrigin //解決跨域問題 public class DailyController {@Autowiredprivate DailyService dailyService;.............//圖表顯示,返回兩部分?jǐn)?shù)據(jù),日期json數(shù)組,數(shù)量json數(shù)組@GetMapping("/showData/{type}/{begin}/{end}")public R showData(@PathVariable String type,@PathVariable String begin,@PathVariable String end){Map<String,Object> map = dailyService.getShowData(type,begin,end);return R.ok().data(map);}}2、service
- 接口
- impl
- 測試
四、前后端整合
1、創(chuàng)建api
guli-admin\src\api\sta.js中添加方法
import request from '@/utils/request' //引入已經(jīng)封裝好的axios 和 攔截器export default {.......//圖表顯示getShowData(searchObj) {return request({url: `/staservice/daily/showData/${searchObj.type}/${searchObj.begin}/${searchObj.end}`,method: 'get'})}}2、show.vue中引入api模塊
import staApi from '@/api/sta.js'3、js腳本
export default {data() {return {searchObj: {begin: "",end: "",type: "",},btnDisabled: false,chart: null,title: "",xData: [],yData: [],};},methods: {setChart() {// 基于準(zhǔn)備好的dom,初始化echarts實例this.chart = echarts.init(document.getElementById("chart"));// console.log(this.chart)// 指定圖表的配置項和數(shù)據(jù)var option = {// xAxis: {type: "category",data:this.xData,//x軸數(shù)據(jù)},// yAxis: {type: "value",},series: [{// 系列中的數(shù)據(jù)內(nèi)容數(shù)組data:this.yData,//y軸數(shù)據(jù)// 折線圖type: "line",//type 決定自己的圖表類型},],};this.chart.setOption(option);},showChart(){staApi.getShowData(this.searchObj).then(resp=>{//x軸 時間this.xData = resp.data.xlist//y軸 數(shù)據(jù)this.yData = resp.data.ylist//調(diào)用下面生成圖表方法,改變值this.setChart();})}},created() {}, }; </script>- 測試
五、樣式調(diào)整
參考配置手冊: https://echarts.baidu.com/option.html#title
- 寫到option里面
1、顯示標(biāo)題
title: {text: this.title },2、x坐標(biāo)軸觸發(fā)提示
tooltip: {trigger: 'axis' },3、區(qū)域縮放
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,}, ],總結(jié)
以上是生活随笔為你收集整理的Day215.课程详细页面功能完善、Echarts统计分析模块[生成统计数据+生成图表]前后端整合 -谷粒学院的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU 1517 A Multiplic
- 下一篇: Docker应用学习