一、前语
咱们好!我是sum墨,一个一线的底层码农,平常喜爱研讨和考虑一些技能相关的问题并收拾成文,限于本人水平,假如文章和代码有表述不当之处,还请不吝赐教。
咱们在开发项目的时分,都会衔接数据库。有时分遇到问题需求根据咱们编写的SQL进行分析,但假如不进行一些开发或许装备的话,这些SQL是不会打印到控制台的,它们默许是躲藏的。下面给咱们介绍几种常用的方法。
二、打印方式
1. 代码方式
Mybatis结构是Java程序员最常用的数据库映射结构,
MyBatis 答应你在已映射句子履行过程中的某一点进行阻拦调用。默许情况下,MyBatis 答应运用插件来阻拦的方法调用。
那么咱们能够根据这个机制来获取咱们履行的sql句子以及参数。下面的SqlExecuteTimeCountInterceptor.java直接复制到SpringBoot项目
就能够运用了。
(1)代码如下
package com.example.springbootsqlmonitor.config;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
@Component
public class SqlExecuteTimeCountInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(SqlExecuteTimeCountInterceptor.class);
/**
* 打印的参数字符串的最大长度
*/
private final static int MAX_PARAM_LENGTH = 50;
/**
* 记载的最大SQL长度
*/
private final static int MAX_SQL_LENGTH = 500;
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget();
long startTime = System.currentTimeMillis();
StatementHandler statementHandler = (StatementHandler) target;
try {
return invocation.proceed();
} finally {
long endTime = System.currentTimeMillis();
long timeCount = endTime - startTime;
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
// 格局化Sql句子,去除换行符,替换参数
sql = formatSQL(sql, parameterObject, parameterMappingList);
logger.info("履行 SQL:[{}]履行耗时[ {} ms])", sql, timeCount);
}
}
/**
* 格局化/美化 SQL句子
*
* @param sql sql 句子
* @param parameterObject 参数的Map
* @param parameterMappingList 参数的List
* @return 格局化之后的SQL
*/
private String formatSQL(String sql, Object parameterObject, List<ParameterMapping> parameterMappingList) {
// 输入sql字符串空判断
if (sql == null || sql.length() == 0) {
return "";
}
// 美化sql
sql = beautifySql(sql);
// 不传参数的场景,直接把sql美化一下回来出去
if (parameterObject == null || parameterMappingList == null || parameterMappingList.size() == 0) {
return sql;
}
return limitSQLLength(sql, parameterObject, parameterMappingList);
}
/**
* 回来限制长度之后的SQL句子
*
* @param sql 原始SQL句子
* @param parameterObject
* @param parameterMappingList
*/
private String limitSQLLength(String sql, Object parameterObject, List<ParameterMapping> parameterMappingList) {
if (sql == null || sql.length() == 0) {
return "";
}
Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
StringBuilder paramsBuilder = new StringBuilder("n参数列表:");
parameterMap.forEach((key, value) -> {
parameterMappingList.forEach(parameterMapping -> {
if (parameterMapping.getProperty().equals(key)) {
String detail = "[" + key + ":" + value + "];";
paramsBuilder.append(detail);
}
});
});
sql += paramsBuilder.toString();
if (sql.length() > MAX_SQL_LENGTH) {
return sql.substring(0, MAX_SQL_LENGTH);
} else {
return sql;
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
/**
* 美化sql
*
* @param sql sql句子
*/
private String beautifySql(String sql) {
sql = sql.replaceAll("[\sn ]+", " ");
return sql;
}
}
(2)作用如下
2022-07-21 19:14:07.685 INFO 25936 --- [ main] c.e.s.c.SqlExecuteTimeCountInterceptor : 履行 SQL:[SELECT t3.user_id, t3.user_name, t2.role_id, t2.role_name FROM my_user_role_rel t1 LEFT JOIN my_role t2 ON t1.role_id = t2.role_id LEFT JOIN my_user t3 ON t1.user_id = t3.user_id WHERE t1.user_id = ? AND t2.role_id = ?
参数列表:[roleId:1];[userId:1];]履行耗时[ 18 ms])
2. Mybatis-Plus装备
假如你的项目用的是Mybatis-Plus结构,那么你能够不必写代码,直接用一行装备就能够完成sql日志监控:
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
(1)装备如下
# mybatis
mybatis.configuration.auto-mapping-behavior=full
mybatis.configuration.map-underscore-to-camel-case=true
mybatis-plus.mapper-locations=classpath*:/mybatis/mapper/*.xml
# 敞开mybatis-plus自带SQL打印
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
(2)作用如下
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@b14b60a] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1142d377] will not be managed by Spring
==> Preparing: SELECT t3.user_id, t3.user_name, t2.role_id, t2.role_name FROM my_user_role_rel t1 LEFT JOIN my_role t2 ON t1.role_id = t2.role_id LEFT JOIN my_user t3 ON t1.user_id = t3.user_id WHERE t1.user_id = ?
==> Parameters: 1(Long)
<== Columns: user_id, user_name, role_id, role_name
<== Row: 1, 用户1, 1, 超级管理员
<== Row: 1, 用户1, 2, 游客
<== Total: 2
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@b14b60a]
3. 整合p6spy结构
运用p6spy这种方式是最复杂的,不过也是最好的,这个结构是专门用来盯梢数据库操作的。
(1)maven引入
<!-- sql 打印 -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.8.5</version>
</dependency>
(2)application.properties装备文件
修正原有的装备,这儿要注意改两个当地:
- spring.datasource.url=
jdbc:p6spy:mysql:
//localhost:3306/mybatis-test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true - spring.datasource.driver-class-name=
com.p6spy.engine.spy.P6SpyDriver
完整的装备如下
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatis-test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=***
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
(3)在resources下创立spy.properties文件
内容如下:
# 敞开模块sql记载和长时sql记载
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自己编写格局类
logMessageFormat=com.example.springbootsqlmonitor.config.P6spySqlFormatConfig
# 经过装备进行格局设置
#logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
# 自定义sql输出格局
#customLogMessageFormat=%(currentTime) | TIMEuFF1A %(executionTime) ms | SQLuFF1A %(sql)
# 日志输出方式(输出到控制台)
appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
excludecategories=info,debug,result,resultset
deregisterdrivers=true
dateformat=yyyy-MM-dd HH:mm:ss
driverlist=com.mysql.cj.jdbc.Driver
# 敞开长时sql记载
outagedetection=true
# 触发长时记载时限
outagedetectioninterval=2
这儿有一个
logMessageFormat
特点,它能够运用自己编写的格局进行打印,做法也很简单,就是添加一打印的类,然后把类途径复制过来,这儿我贴一下我常用的格局,
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
public class P6spySqlFormatConfig implements MessageFormattingStrategy {
@Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared,
String sql, String url) {
return StringUtils.isNotBlank(sql) ? formatFullTime(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss") + " | 耗时 "
+ elapsed + " ms | SQL 句子:" + "n" + sql.replaceAll("[s]+", " ") + ";" : "";
}
public static String formatFullTime(LocalDateTime localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return localDateTime.format(dateTimeFormatter);
}
}
(4)作用如下
耗时 5 ms | SQL 句子:
SELECT t3.user_id, t3.user_name, t2.role_id, t2.role_name FROM my_user_role_rel t1 LEFT JOIN my_role t2 ON t1.role_id = t2.role_id LEFT JOIN my_user t3 ON t1.user_id = t3.user_id WHERE t1.user_id = 1 AND t2.role_id = 1;
(5)整合p6spy遇到的一些问题
启动报错
Caused by: java.lang.IllegalStateException: dbType not support : null, url jdbc:p6spy:mysql://localhost:3306/mybatis-test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull
呈现这个问题的原因是装备了Druid衔接池,是它的一个特点导致的,把这个特点注释掉
spring.datasource.druid.filters=stat,wall
或许添加如下装备:
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.stat.db-type=mysql
spring.datasource.druid.filter.stat.enabled=true
spy.properties装备文件不收效
呈现这个问题,一般要去检查一下你的jar包,看一下spy.properties文件有没有被打包进去。因为这个是不需求添加装备类的,是
经过绑架数据库衔接完成的
。
三、总结一下
比照上面这三种方式,其中p6spy打印的sql最完整,是能够直接放在数据库工具上履行的,而不是像Mybatis打印那种参数带问号的。不过打印这些sql句子都挺耗费功能的,建议到了线上把它给关掉,避免非事务耗费资源。