Springboot中分析SQL性能的兩種方式詳解
SQL性能分析的兩種方式:
功能介紹
- 記錄 SQL 執(zhí)行時(shí)間,超過閾值會(huì)進(jìn)行警告
- 打印完整的 SQL 語句,便于調(diào)試和優(yōu)化
- 適用于開發(fā)和測(cè)試環(huán)境,生產(chǎn)環(huán)境建議關(guān)閉
實(shí)現(xiàn)方式:
方式一:使用 MyBatis-Plus 性能分析插件
首先需要在MyBatis-Plus
配置類中配置PerformanceInterceptor
插件:
@Configuration public class MyBatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 添加分頁攔截器(如果使用分頁) interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 添加性能分析攔截器 PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(500); // SQL 最大執(zhí)行時(shí)間(毫秒),超過自動(dòng)警告 performanceInterceptor.setFormat(true); // 是否格式化 SQL 語句 interceptor.addInnerInterceptor(performanceInterceptor); return interceptor; } }
配置項(xiàng)說明:
配置項(xiàng) | 說明 | 示例 |
---|---|---|
setMaxTime(long maxTime) | 設(shè)置 SQL 執(zhí)行的最大時(shí)長(單位:ms),超過時(shí)間將拋出異常,默認(rèn) -1(不限制) | performanceInterceptor.setMaxTime(500); // 超過 500ms 警告 |
setFormat(boolean format) | 是否格式化 SQL,默認(rèn) false ,開啟后會(huì)美化 SQL 輸出 | performanceInterceptor.setFormat(true); |
日志輸出:
當(dāng)查詢執(zhí)行時(shí)間超過 maxTime
限制時(shí),控制臺(tái)會(huì)輸出:
[SQL] ==> Preparing: SELECT * FROM orders WHERE status = ?
[SQL] ==> Parameters: 1(Integer)
[SQL] <== Total Time: 850 ms (超過最大時(shí)間 500ms,可能存在性能問題)
由于MyBatis-Plus 3.4.0
以后已經(jīng)將上述插件棄用,所以如果你使用高版本的MyBatis-Plus
,推薦使用方式二.
方式二:使用p6spy
框架 效果圖:
實(shí)現(xiàn)步驟:
1.引入pom
依賴:
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.9.1</version> </dependency>
2.首先在 springboot
配置類中加入配置:
- 把原來的
JDBC Driver
替換為com.p6spy.engine.spy.P6SpyDriver
. - 在原來
url
的jdbc
:后面添加p6spy
:,比如jdbc:p6spy:mysql://127.0.0.1:3306/databse
- 添加
p6spy
的配置文件spy.properties
.
配置文件內(nèi)容如下:
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory # 自定義日志打印 logMessageFormat=warren.reggie.common.P6SpyLogger #logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat #customLogMessageFormat=%(currentTime) | SQL耗時(shí): %(executionTime) ms | 連接信息: %(category)-%(connectionId) | 執(zhí)行語句: %(sql)# 使用控制臺(tái)記錄sql appender=com.p6spy.engine.spy.appender.StdoutLogger ## 配置記錄Log例外 excludecategories=info,debug,result,batc,resultset # 設(shè)置使用p6spy driver來做代理 deregisterdrivers=true # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 實(shí)際驅(qū)動(dòng) driverlist=com.mysql.jdbc.Driver # 是否開啟慢SQL記錄 outagedetection=true # 慢SQL記錄標(biāo)準(zhǔn)秒 outagedetectioninterval=2
3.自定義日志輸出格式:
首先創(chuàng)建P6SpyLogger
類:
package warren.reggie.common; import com.p6spy.engine.spy.appender.MessageFormattingStrategy; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * 自定義 P6Spy SQL 日志格式(帶顏色) * author: Warren */public class P6SpyLogger implements MessageFormattingStrategy { // ANSI 顏色代碼 private static final String RESET = "\u001B[0m"; // 重置顏色 private static final String RED = "\u001B[31m"; // 紅色(高亮錯(cuò)誤) private static final String GREEN = "\u001B[32m"; // 綠色(SQL 語句) private static final String YELLOW = "\u001B[33m";// 黃色(執(zhí)行時(shí)間) private static final String BLUE = "\u001B[34m"; // 藍(lán)色(分類) private static final String CYAN = "\u001B[36m"; // 青色(連接 ID) /** * 自定義 SQL 日志格式(帶顏色) * * @param connectionId 連接 ID * @param now 當(dāng)前時(shí)間(P6Spy 傳遞的) * @param elapsed SQL 執(zhí)行時(shí)間(ms) * @param category SQL 類型(如 statement、commit、rollback) * @param prepared 預(yù)編譯 SQL(帶 ? 占位符) * @param sql 真實(shí) SQL 語句(占位符替換后的) * @param url 數(shù)據(jù)庫連接 URL * @return 格式化后的日志字符串 */ @Override public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) { // 過濾空 SQL if (sql == null || sql.trim().isEmpty()) { return ""; } // 格式化當(dāng)前時(shí)間 String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // 構(gòu)造帶顏色的日志輸出 return String.format( "%s[%s]%s | %s耗時(shí): %d ms%s | %s連接: %d%s | %s分類: %s%s\n%s執(zhí)行 SQL: %s%s;\n", CYAN, currentTime, RESET, // 時(shí)間(青色) YELLOW, elapsed, RESET, // 執(zhí)行時(shí)間(黃色) BLUE, connectionId, RESET, // 連接 ID(藍(lán)色) RED, category, RESET, // 分類(紅色) GREEN, sql.trim(), RESET // SQL 語句(綠色) ); } }
然后將配置文件中的格式化器屬性改為自己的類 :
# 自定義日志打印 logMessageFormat=warren.reggie.common.P6SpyLogger
到此這篇關(guān)于Springboot中分析SQL性能的兩種方式詳解的文章就介紹到這了,更多相關(guān)Springboot 分析sql性能內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot連接PostgreSQL+MybatisPlus入門案例(代碼詳解)
- SpringBoot整合Flink CDC實(shí)現(xiàn)實(shí)時(shí)追蹤mysql數(shù)據(jù)變動(dòng)
- Springboot整合Mybatis和SQLite的詳細(xì)過程
- SpringBoot項(xiàng)目整合MybatisPlus并使用SQLite作為數(shù)據(jù)庫的過程
- SpringBoot整合Druid實(shí)現(xiàn)SQL監(jiān)控和數(shù)據(jù)庫密碼加密
- SpringBoot集成Druid監(jiān)控慢SQL的詳細(xì)過程
相關(guān)文章
SpringBoot中TransactionTemplate事務(wù)管理的實(shí)現(xiàn)
Spring Boot提供了多種方式來管理事務(wù),其中之一是使用TransactionTemplate,本文主要介紹了SpringBoot中TransactionTemplate事務(wù)管理的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04java?Springboot對(duì)接開發(fā)微信支付詳細(xì)流程
最近要做一個(gè)微信小程序,需要微信支付,所以研究了下怎么在java上集成微信支付功能,下面這篇文章主要給大家介紹了關(guān)于java?Springboot對(duì)接開發(fā)微信支付的相關(guān)資料,需要的朋友可以參考下2024-08-08解決MyBatisPlus的updateBatchById()批量修改失效問題
這篇文章主要介紹了解決MyBatisPlus的updateBatchById()批量修改失效問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08Java創(chuàng)建內(nèi)部類對(duì)象實(shí)例詳解
這篇文章主要介紹了Java創(chuàng)建內(nèi)部類對(duì)象實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05Spring多數(shù)據(jù)源導(dǎo)致配置失效的解決
這篇文章主要介紹了Spring多數(shù)據(jù)源導(dǎo)致配置失效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01Spring Boot中使用Redis做緩存的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于Spring Boot中使用Redis做緩存的相關(guān)資料,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2017-06-06Java異常處理運(yùn)行時(shí)異常(RuntimeException)詳解及實(shí)例
這篇文章主要介紹了 Java異常處理運(yùn)行時(shí)異常(RuntimeException)詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下http://time.qq.com/?pgv_ref=aiotime2017-05-05自動(dòng)配置@EnableAutoConfiguration問題
這篇文章主要介紹了自動(dòng)配置@EnableAutoConfiguration問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06