当前位置:网站首页>聊聊如何利用p6spy进行sql监控
聊聊如何利用p6spy进行sql监控
2022-07-03 05:14:00 【linyb极客之路】
前言
1、p6spy简介
P6Spy 是一个框架,无需对现有应用程序进行任何代码更改,即可无缝拦截和记录数据库数据。通过 P6Spy 我们可以对 SQL 语句进行拦截,相当于一个 SQL 语句的记录器,这样我们可以用它来作相关的分析,比如性能分析
2、实现原理
p6spy将应用的数据源给劫持了,应用操作数据库其实在调用p6spy的数据源,p6spy劫持到需要执行的sql或者hql之类的语句之后,他自己去调用一个realDatasource,再去操作数据库
3、相关官方文档
github:https://github.com/p6spy/p6spy
官网:https://p6spy.readthedocs.io/en/latest/index.html
p6spy使用
1、在项目中的pom引入相关的GAV
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>${p6spy.version}</version> </dependency>
2、切换项目中的jdbc驱动以及数据源
改成如下内容
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driverClassName: ${DRIVER_CALSS_NAME:com.p6spy.engine.spy.P6SpyDriver} url: ${DATASOURCE_URL:jdbc:p6spy:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai} username: ${DATASOURCE_USERNAME:root} password: ${DATASOURCE_PWD:123456}
3、在resource目录下添加spy.properties
配置如示例下内容
#3.2.1以上使用modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory#3.2.1以下使用或者不配置#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory# 自定义日志打印#logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLoggerlogMessageFormat=com.github.lybgeek.p6spy.extentsion.CustomP6SpyLogger#日志输出到控制台#appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger# 使用日志系统记录 sql#appender=com.p6spy.engine.spy.appender.Slf4JLoggerappender=com.github.lybgeek.p6spy.extentsion.CustomStdoutLogger# 设置 p6spy driver 代理deregisterdrivers=true# 取消JDBC URL前缀useprefix=true# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.excludecategories=info,debug,result,commit,resultset# 日期格式dateformat=yyyy-MM-dd HH:mm:ss# 实际驱动可多个#driverlist=org.h2.Driver# 是否开启慢SQL记录outagedetection=true# 慢SQL记录标准 2 秒outagedetectioninterval=2
4、自定义日志格式【可选】
public class CustomP6SpyLogger implements MessageFormattingStrategy { /** * Sql日志格式化 * * @param connectionId: 连接ID * @param now: 当前时间 * @param elapsed: 花费时间 * @param category: 类别 * @param prepared: 预编译SQL * @param sql: 最终执行的SQL * @param url: 数据库连接地址 * @return 格式化日志结果 */ @Override public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) { return StringUtils.isNotBlank(sql) ? " 耗时:" + elapsed + " ms " + now + "\n 执行 SQL:" + sql.replaceAll("[\\s]+", " ") + "\n" : ""; }}
在spy.properties中配置自定义日志格式
logMessageFormat=com.github.lybgeek.p6spy.extentsion.CustomP6SpyLogger
5、自定义日志输出【可选】
public class CustomStdoutLogger extends com.p6spy.engine.spy.appender.StdoutLogger{ @Override public void logText(String text) { System.out.println("sql:" + text); }}
在spy.properties中配置自定义日志输出
appender=com.github.lybgeek.p6spy.extentsion.CustomStdoutLogger
6、测试观察控制台输出
sql: 耗时:1 ms 2022-05-10 11:38:34 执行 SQL:SELECT id,username,password,fullname,mobile,email FROM t_user
总结
p6spy可以根据sql的执行效率分析sql对sql进行优化,但因为p6spy会对性能有一定影响,因此不适合在正式环境上使用。此外关于p6spy更详细的配置可以查看如下链接 https://p6spy.readthedocs.io/en/latest/configandusage.html
demo链接
https://github.com/lyb-geek/springboot-learning/tree/master/springboot-p6spy
边栏推荐
- Rust基础入门之(基本类型)
- (完美解决)matplotlib图例(legend)如何自由设置其位置
- Go practice - gorilla / handlers used by gorilla web Toolkit
- 1086 tree traversals again (25 points)
- The process of browser accessing the website
- 谷歌 | 蛋白序列的深度嵌入和比对
- 大学校园IP网络广播-厂家基于校园局域网的大学校园IP广播方案设计指南
- Maximum continuous sub segment sum (dynamic programming, recursive, recursive)
- Introduction to redis and explanation of data types
- Bluebridge cup real topic 2020 palindrome date simulation construction provincial competition
猜你喜欢
[batch dos-cmd command - summary and summary] - CMD window setting and operation command - close CMD window and exit CMD environment (exit, exit /b, goto: EOF)
2022-02-11 daily clock in: problem fine brush
Retirement plan fails, 64 year old programmer starts work again
How to connect the network: Chapter 2 (Part 1): a life cycle of TCP connection | CSDN creation punch in
XML配置文件
[basic grammar] Snake game written in C language
Detailed explanation of the output end (head) of yolov5 | CSDN creation punch in
[research materials] annual report of China's pension market in 2021 - Download attached
微服务常见面试题
BIO、NIO、AIO区别
随机推荐
1115 counting nodes in a BST (30 points)
Silent authorization login and registration of wechat applet
酒店公共广播背景音乐-基于互联网+的酒店IP网络广播系统设计
Appium 1.22. L'Inspecteur appium après la version X doit être installé séparément
Based on RFC 3986 (unified resource descriptor (URI): general syntax)
The process of browser accessing the website
RT thread flow notes I startup, schedule, thread
Yolov5 input (I) -- mosaic data enhancement | CSDN creative punch in
sql语句模糊查询遇到的问题
1087 all roads lead to Rome (30 points)
Actual combat 8051 drives 8-bit nixie tube
[set theory] relationship properties (common relationship properties | relationship properties examples | relationship operation properties)
[clock 223] [binary tree] [leetcode high frequency]: 102 Sequence traversal of binary tree
Online VR model display - 3D visual display solution
Promise
Go practice -- closures in golang (anonymous functions, closures)
Kept hot standby and haproxy
Common methods of JS array
Realize file download through the tag of < a > and customize the file name
leetcode435. Non overlapping interval