首頁 > 軟體

SpringBoot整合P6Spy實現SQL紀錄檔的記錄詳解

2022-11-28 22:00:26

P6Spy簡介

P6Spy是一個可以用來在應用程式中攔截和修改資料操作語句的開源框架。

通過P6Spy可以對SQL語句進行攔截,相當於一個SQL語句的記錄器,這樣我們可以用它來作相關的分析,比如效能分析。

應用場景

pom

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
    </dependencies>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    #driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/course_db?serverTimezone=GMT%2B8
    # url: jdbc:p6spy:mysql://localhost:3306/course_db?serverTimezone=GMT%2B8
    username: root
    password: root

# 開啟mybatis-plus的sql紀錄檔輸出
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

entity

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("course_1")
public class Course {
    @TableField("cid")
    private Long cId;
    private String cName;
    private Integer userId;
    private String cStatus;
}

Mapper

public interface CourseMapper extends BaseMapper<Course> {
}

啟動類

@SpringBootApplication
@MapperScan(basePackages = "cn.zysheep.mapper")
public class ShardingjdbcdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShardingjdbcdemoApplication.class, args);
    }
}

測試類

@SpringBootTest
@Slf4j
class ShardingjdbcdemoApplicationTests {
    @Autowired
    private CourseMapper courseMapper;
    @SneakyThrows
    @Test
    void findCourse() {
        courseMapper.selectList(null).forEach(System.out::println);
    }
}

mybatis-plus也可以列印輸出的sql紀錄檔,但是不是我們想要的效果,如何來控制想要的sql紀錄檔輸出,可以使用P6Spy開源產品。

P6Spy入門使用

spy.properties

resources目錄新增組態檔,類似log4j.xml,記錄設定資訊

module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# sql紀錄檔列印輸出
# 1、logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
# 2、logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
# customLogMessageFormat=%(currentTime) | SQL use time: %(executionTime) ms | connect info: %(category)-%(connectionId) | execute sql: %(sql)
# 3、自定義紀錄檔列印(全限定類名)
logMessageFormat=cn.zysheep.config.P6SPYConfig
# 使用紀錄檔系統記錄sql
appender=com.p6spy.engine.spy.appender.Slf4JLogger
## 設定記錄Log例外
excludecategories=info,debug,result,batc,resultset
# 設定使用p6spy driver來做代理
deregisterdrivers=true
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 實際驅動
driverlist=com.mysql.cj.jdbc.Driver
# 是否開啟慢SQL記錄
outagedetection=true
# 慢SQL記錄標準 秒
outagedetectioninterval=2

P6Spy有內建的SQL輸出格式,如上組態檔。這裡我們使用自定義SQL紀錄檔列印

P6SPYConfig

public class P6SPYConfig  implements MessageFormattingStrategy {
    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
        Map<String, Object> message = new LinkedHashMap<>(8);
        String newPrepared = prepared.replace("   ", "").replace("n", " ");
        message.put("prepared", newPrepared);
        String newSql = sql.replace("   ", "").replace("n", " ");
        message.put("sql", newSql);
        return JSONObject.toJSONString(message, true);
    }
}

application.yml

spring:
  datasource:
    # driver-class-name: com.mysql.cj.jdbc.Driver
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    type: com.alibaba.druid.pool.DruidDataSource
    #  url: jdbc:mysql://localhost:3306/course_db?serverTimezone=GMT%2B8
    url: jdbc:p6spy:mysql://localhost:3306/course_db?serverTimezone=GMT%2B8
    username: root
    password: root

# 開啟mybatis-plus的sql紀錄檔輸出
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

測試類不變

到此這篇關於SpringBoot整合P6Spy實現SQL紀錄檔的記錄詳解的文章就介紹到這了,更多相關SpringBoot整合P6Spy內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com