博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
0216 aop和打印数据库执行日志
阅读量:4210 次
发布时间:2019-05-26

本文共 2488 字,大约阅读时间需要 8 分钟。

需求

image.png

maven依赖

image.png

p6spy
p6spy
3.8.7
com.google.guava
guava
28.2-jre
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true

打印sql

配置要点:

1. 驱动配置 application.properties

spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriverspring.datasource.url=jdbc:p6spy:mysql://localhost:3306/demo_datasource

2. psy配置

# 单行日志logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat# 使用Slf4J记录sqlappender=com.p6spy.engine.spy.appender.Slf4JLogger# 是否开启慢SQL记录outagedetection=true# 慢SQL记录标准,单位秒outagedetectioninterval=2

aop打印持久层执行时间

使用aop实现;

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@Slf4jpublic 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注解:

@EnableAspectJAutoProxy(proxyTargetClass = true)

小结

来个效果截图:

image.png

通过本片文章,你可以学会:

1. 给代码添加aop切面,增加日志或者打印出方法执行总耗时;

1. 给你的数据持久层打印出所有的sql语句,方便生产环境排查问题;

希望大家平安度过冠疫!每天持续精进!

image.png

原创不易,转载请注明出处,欢迎多沟通交流

你可能感兴趣的文章
fcntl函数总结
查看>>
HTML条件注释
查看>>
Putty远程服务器的SSH经验
查看>>
内核态与用户态
查看>>
使用mingw(fedora)移植virt-viewer
查看>>
趣链 BitXHub跨链平台 (4)跨链网关“初介绍”
查看>>
C++ 字符串string操作
查看>>
MySQL必知必会 -- 了解SQL和MySQL
查看>>
MySQL必知必会 -- 使用MySQL
查看>>
MySQL必知必会 -- 数据检索
查看>>
MySQL必知必会 -- 排序检索数据 ORDER BY
查看>>
MySQL必知必会 -- 数据过滤
查看>>
MYSQL必知必会 -- 用通配符进行过滤
查看>>
MYSQL必知必会 -- 用正则表达式进行搜索
查看>>
MySQL必知必会 -- 创建计算字段
查看>>
MySQL必知必会 -- 使用数据处理函数
查看>>
MySQL必知必会 -- 数据汇总
查看>>
MySQL必知必会 -- 子查询的使用
查看>>
POJ 3087 解题报告
查看>>
POJ 2536 解题报告
查看>>