0216 aop和打印數據庫執行日誌

需求

image.png

maven依賴

image.png

<dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.8.7</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

打印sql

配置要點:java

  1. 驅動配置 application.properties
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/demo_datasource
  1. psy配置
# 單行日誌
logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
# 使用Slf4J記錄sql
appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 是否開啓慢SQL記錄
outagedetection=true
# 慢SQL記錄標準,單位秒
outagedetectioninterval=2

aop打印持久層執行時間

使用aop實現;mysql

package com.springbootpractice.demo.p6spy.aop;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * 說明:aop配置
 * @author carter
 * 建立時間: 2020年02月16日 8:49 下午
 **/
@Aspect
@Component
@Slf4j
public class PrintTimeCostAspectJConfig {

    @SneakyThrows
    @Around("myPointCut()")
    public Object around(ProceedingJoinPoint pj) {
        Object res = null;
        String methodName = pj.getSignature().toShortString();
        StopWatch stopWatch = new StopWatch(methodName);
        stopWatch.start();
        try {
            res = pj.proceed();
        } catch (Throwable ex) {
            throw ex;
        } finally {
            stopWatch.stop();
            log.warn("{}執行耗時{}毫秒", methodName, stopWatch.getTotalTimeMillis());
        }
        return res;
    }

    @Pointcut("execution(* com.springbootpractice.demo.p6spy.web..*(..))")
    public void myPointCut() {
    }

}

啓用aop註解:git

@EnableAspectJAutoProxy(proxyTargetClass = true)

小結

來個效果截圖:
image.pnggithub

經過本片文章,你能夠學會:web

  1. 給代碼添加aop切面,增長日誌或者打印出方法執行總耗時;
  2. 給你的數據持久層打印出全部的sql語句,方便生產環境排查問題;

但願你們平安度過冠疫!天天持續精進!spring

image.png

代碼點我!sql

原創不易,轉載請註明出處。springboot

相關文章
相關標籤/搜索