guli_statistics
guli_statistics.sql
service_statistics
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?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
#返回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
@SpringBootApplication
@MapperScan("com.atguigu.staservice.mapper")
@ComponentScan("com.atguigu")
@EnableDiscoveryClient
@EnableFeignClients
public class StaApplication {
public static void main(String[] args) {
SpringApplication.run(StaApplication.class, args);
}
}
controller
@GetMapping(value = "countregister/{day}")
public R registerCount(
@PathVariable String day){
Integer count = memberService.countRegisterByDay(day);
return R.ok().data("countRegister", count);
}
@Override
public Integer countRegisterByDay(String day) {
return baseMapper.selectRegisterCount(day);
}
创建client包和UcenterClient接口
@Component
@FeignClient("service-ucenter")
public interface UcenterClient {
@GetMapping(value = "/ucenterservice/member/countregister/{day}")
public R registerCount(@PathVariable("day") String day);
}
service
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl implements StatisticsDailyService {
@Autowired
private UcenterClient ucenterClient;
@Override
public void createStatisticsByDay(String day) {
//删除已存在的统计对象
QueryWrapper dayQueryWrapper = new QueryWrapper<>();
dayQueryWrapper.eq("date_calculated", day);
baseMapper.delete(dayQueryWrapper);
//获取统计信息
Integer registerNum = (Integer) ucenterClient.registerCount(day).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);
}
}
@PostMapping("{day}")
public R createStatisticsByDate(@PathVariable String day) {
dailyService.createStatisticsByDay(day);
return R.ok();
}
复制日期工具类
@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);
}
}
3、在线生成cron表达式
http://cron.qqe2.com/
location ~ /staservice/ {
proxy_pass http://localhost:8008;
}
创建src/api/sta.js
import request from '@/utils/request'
const api_name = '/admin/statistics/daily'
export default {
createStatistics(day) {
return request({
url: `${api_name}/${day}`,
method: 'post'
})
}
}
src/router/index.js
{
path: '/statistics/daily',
component: Layout,
redirect: '/statistics/daily/create',
name: 'Statistics',
meta: { title: '统计分析', icon: 'chart' },
children: [
{
path: 'create',
name: 'StatisticsDailyCreate',
component: () => import('@/views/statistics/daily/create'),
meta: { title: '生成统计' }
}
]
},
src/views/statistics/daily/create.vue
模板部分
生成
script部分
ECharts是百度的一个项目,后来百度把Echart捐给apache,用于图表展示,提供了常规的折线图、柱状图、散点图、饼图、K线图,用于统计的盒形图,用于地理数据可视化的地图、热力图、线图,用于关系数据可视化的关系图、treemap、旭日图,多维数据可视化的平行坐标,还有用于 BI 的漏斗图,仪表盘,并且支持图与图之间的混搭。
官方网站:https://echarts.baidu.com/
入门参考:官网->文档->教程->5分钟上手ECharts
(1)创建html页面:柱图.html
(2)引入ECharts
(3)定义图表区域
(4)渲染图表
实例参考:官网->实例->官方实例 https://echarts.baidu.com/examples/
折线图.html
npm install --save [email protected]
src/router/index.js
在统计分析路由中增加子路由
{
path: 'chart',
name: 'StatisticsDayChart',
component: () => import('@/views/statistics/daily/chart'),
meta: { title: '统计图表' }
}
src/views/statistics/daily/chart.vue
模板
查询
js:暂时显示临时数据
@GetMapping("show-chart/{begin}/{end}/{type}")
public R showChart(@PathVariable String begin,@PathVariable String end,@PathVariable String type){
Map map = dailyService.getChartData(begin, end, type);
return R.ok().data(map);
}
接口
Map getChartData(String begin, String end, String type);
实现
@Override
public Map getChartData(String begin, String end, String type) {
QueryWrapper dayQueryWrapper = new QueryWrapper<>();
dayQueryWrapper.select(type, "date_calculated");
dayQueryWrapper.between("date_calculated", begin, end);
List dayList = baseMapper.selectList(dayQueryWrapper);
Map map = new HashMap<>();
List dataList = new ArrayList();
List dateList = new ArrayList();
map.put("dataList", dataList);
map.put("dateList", dateList);
for (int i = 0; i < dayList.size(); i++) {
Daily daily = dayList.get(i);
dateList.add(daily.getDateCalculated());
switch (type) {
case "register_num":
dataList.add(daily.getRegisterNum());
break;
case "login_num":
dataList.add(daily.getLoginNum());
break;
case "video_view_num":
dataList.add(daily.getVideoViewNum());
break;
case "course_num":
dataList.add(daily.getCourseNum());
break;
default:
break;
}
}
return map;
}
src/api/statistics/daily.js中添加方法
showChart(searchObj) {
return request({
url: `${api_name}/show-chart/${searchObj.begin}/${searchObj.end}/${searchObj.type}`,
method: 'get'
})
}
import daily from '@/api/statistics/daily'
......
showChart() {
this.initChartData()
// this.setChart()//放在initChartData回调中执行
},
// 准备图表数据
initChartData() {
daily.showChart(this.searchObj).then(response => {
// 数据
this.yData = response.data.dataList
// 横轴时间
this.xData = response.data.dateList
// 当前统计类别
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()
})
},
xAxis: {
type: 'category',
data: this.xData//-------绑定数据
},
// y轴是数据轴(连续数据)
yAxis: {
type: 'value'
},
// 系列列表。每个系列通过 type 决定自己的图表类型
series: [{
// 系列中的数据内容数组
data: this.yData,//-------绑定数据
// 折线图
type: 'line'
}],
参考配置手册:https://echarts.baidu.com/option.html#title
title: {
text: this.title
},
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
}]
在前面的统计分析功能中,我们采取了服务调用获取统计数据,这样耦合度高,效率相对较低,目前我采取另一种实现方式,通过实时同步数据库表的方式实现,例如我们要统计每天注册与登录人数,我们只需把会员表同步到统计库中,实现本地统计就可以了,这样效率更高,耦合度更低,Canal就是一个很好的数据库同步工具。canal是阿里巴巴旗下的一款开源项目,纯Java开发。基于数据库增量日志解析,提供增量数据订阅&消费,目前主要支持了MySQL。
2、Canal环境搭建
canal的原理是基于mysql binlog技术,所以这里一定需要开启mysql的binlog写入功能
开启mysql服务: service mysql start
(1)检查binlog功能是否有开启
mysql> show variables like 'log_bin';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin | OFF |
+---------------+-------+
1 row in set (0.00 sec)
(2)如果显示状态为OFF表示该功能未开启,开启binlog功能
1,修改 mysql 的配置文件 my.cnf
vi /etc/my.cnf
追加内容:
log-bin=mysql-bin #binlog文件名
binlog_format=ROW #选择row模式
server_id=1 #mysql实例id,不能和canal的slaveId重复
2,重启 mysql:
service mysql restart
3,登录 mysql 客户端,查看 log_bin 变量
mysql> show variables like 'log_bin';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin | ON|
+---------------+-------+
1 row in set (0.00 sec)
————————————————
如果显示状态为ON表示该功能已开启
(3)在mysql里面添加以下的相关用户和权限
CREATE USER 'canal'@'%' IDENTIFIED BY 'canal';
GRANT SHOW VIEW, SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%';
FLUSH PRIVILEGES;
下载地址:
https://github.com/alibaba/canal/releases
(1)下载之后,放到目录中,解压文件
cd /usr/local/canal
canal.deployer-1.1.4.tar.gz
tar zxvf canal.deployer-1.1.4.tar.gz
(2)修改配置文件
vi conf/example/instance.properties
#需要改成自己的数据库信息
canal.instance.master.address=192.168.44.132:3306
#需要改成自己的数据库用户名与密码
canal.instance.dbUsername=canal
canal.instance.dbPassword=canal
#需要改成同步的数据库表规则,例如只是同步一下表
#canal.instance.filter.regex=.*\\..*
canal.instance.filter.regex=guli_ucenter.ucenter_member
mysql 数据解析关注的表,Perl正则表达式.
多个正则之间以逗号(,)分隔,转义符需要双斜杠(\\)
常见例子:
1. 所有表:.* or .*\\..*
2. canal schema下所有表: canal\\..*
3. canal下的以canal打头的表:canal\\.canal.*
4. canal schema下的一张表:canal.test1
5. 多个规则组合使用:canal\\..*,mysql.test1,mysql.test2 (逗号分隔)
注意:此过滤条件只针对row模式的数据有效(ps. mixed/statement因为不解析sql,所以无法准确提取tableName进行过滤)
(3)进入bin目录下启动
sh bin/startup.sh
二、创建canal_client模块
1、在guliedu_parent下创建canal_client模块
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
commons-dbutils
commons-dbutils
org.springframework.boot
spring-boot-starter-jdbc
com.alibaba.otter
canal.client
# 服务端口
server.port=10000
# 服务名
spring.application.name=canal-client
# 环境设置:dev、test、prod
spring.profiles.active=dev
# mysql数据库连接
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=root
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry.*;
import com.alibaba.otter.canal.protocol.Message;
import com.google.protobuf.InvalidProtocolBufferException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
@Component
public class CanalClient {
//sql队列
private Queue SQL_QUEUE = new ConcurrentLinkedQueue<>();
@Resource
private DataSource dataSource;
/**
* canal入库方法
*/
public void run() {
CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("192.168.44.132",
11111), "example", "", "");
int batchSize = 1000;
try {
connector.connect();
connector.subscribe(".*\\..*");
connector.rollback();
try {
while (true) {
//尝试从master那边拉去数据batchSize条记录,有多少取多少
Message message = connector.getWithoutAck(batchSize);
long batchId = message.getId();
int size = message.getEntries().size();
if (batchId == -1 || size == 0) {
Thread.sleep(1000);
} else {
dataHandle(message.getEntries());
}
connector.ack(batchId);
//当队列里面堆积的sql大于一定数值的时候就模拟执行
if (SQL_QUEUE.size() >= 1) {
executeQueueSql();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
} finally {
connector.disconnect();
}
}
/**
* 模拟执行队列里面的sql语句
*/
public void executeQueueSql() {
int size = SQL_QUEUE.size();
for (int i = 0; i < size; i++) {
String sql = SQL_QUEUE.poll();
System.out.println("[sql]----> " + sql);
this.execute(sql.toString());
}
}
/**
* 数据处理
*
* @param entrys
*/
private void dataHandle(List entrys) throws InvalidProtocolBufferException {
for (Entry entry : entrys) {
if (EntryType.ROWDATA == entry.getEntryType()) {
RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
EventType eventType = rowChange.getEventType();
if (eventType == EventType.DELETE) {
saveDeleteSql(entry);
} else if (eventType == EventType.UPDATE) {
saveUpdateSql(entry);
} else if (eventType == EventType.INSERT) {
saveInsertSql(entry);
}
}
}
}
/**
* 保存更新语句
*
* @param entry
*/
private void saveUpdateSql(Entry entry) {
try {
RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
List rowDatasList = rowChange.getRowDatasList();
for (RowData rowData : rowDatasList) {
List newColumnList = rowData.getAfterColumnsList();
StringBuffer sql = new StringBuffer("update " + entry.getHeader().getTableName() + " set ");
for (int i = 0; i < newColumnList.size(); i++) {
sql.append(" " + newColumnList.get(i).getName()
+ " = '" + newColumnList.get(i).getValue() + "'");
if (i != newColumnList.size() - 1) {
sql.append(",");
}
}
sql.append(" where ");
List oldColumnList = rowData.getBeforeColumnsList();
for (Column column : oldColumnList) {
if (column.getIsKey()) {
//暂时只支持单一主键
sql.append(column.getName() + "=" + column.getValue());
break;
}
}
SQL_QUEUE.add(sql.toString());
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
/**
* 保存删除语句
*
* @param entry
*/
private void saveDeleteSql(Entry entry) {
try {
RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
List rowDatasList = rowChange.getRowDatasList();
for (RowData rowData : rowDatasList) {
List columnList = rowData.getBeforeColumnsList();
StringBuffer sql = new StringBuffer("delete from " + entry.getHeader().getTableName() + " where ");
for (Column column : columnList) {
if (column.getIsKey()) {
//暂时只支持单一主键
sql.append(column.getName() + "=" + column.getValue());
break;
}
}
SQL_QUEUE.add(sql.toString());
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
/**
* 保存插入语句
*
* @param entry
*/
private void saveInsertSql(Entry entry) {
try {
RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
List rowDatasList = rowChange.getRowDatasList();
for (RowData rowData : rowDatasList) {
List columnList = rowData.getAfterColumnsList();
StringBuffer sql = new StringBuffer("insert into " + entry.getHeader().getTableName() + " (");
for (int i = 0; i < columnList.size(); i++) {
sql.append(columnList.get(i).getName());
if (i != columnList.size() - 1) {
sql.append(",");
}
}
sql.append(") VALUES (");
for (int i = 0; i < columnList.size(); i++) {
sql.append("'" + columnList.get(i).getValue() + "'");
if (i != columnList.size() - 1) {
sql.append(",");
}
}
sql.append(")");
SQL_QUEUE.add(sql.toString());
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
}
/**
* 入库
* @param sql
*/
public void execute(String sql) {
Connection con = null;
try {
if(null == sql) return;
con = dataSource.getConnection();
QueryRunner qr = new QueryRunner();
int row = qr.execute(con, sql);
System.out.println("update: "+ row);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(con);
}
}
}
@SpringBootApplication
public class CanalApplication implements CommandLineRunner {
@Resource
private CanalClient canalClient;
public static void main(String[] args) {
SpringApplication.run(CanalApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
//项目启动,执行canal客户端监听
canalClient.run();
}
}