1.yml配置开关
monitoring:
sql : true
2.拦截器实现
/**
* @author qujingye
* @Classname SqlStatementInterceptor
* @Description sql时间监控
* @Date 2024/4/3 14:56
*/
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class
}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class,
Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})
@Component
@ConditionalOnProperty(prefix = "monitoring", name = "sql", havingValue = "true")
public class SqlStatementInterceptor implements Interceptor {
private static final Logger log = LoggerFactory.getLogger(SqlStatementInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
long timeConsuming = System.currentTimeMillis() - startTime;
log.info("执行SQL:{}ms", timeConsuming);
if (timeConsuming > 999 && timeConsuming < 5000) {
log.info("执行SQL大于1s:{}ms", timeConsuming);
} else if (timeConsuming >= 5000 && timeConsuming < 10000) {
log.info("执行SQL大于5s:{}ms", timeConsuming);
} else if (timeConsuming >= 10000) {
log.info("执行SQL大于10s:{}ms", timeConsuming);
}
}
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties properties) {
Interceptor.super.setProperties(properties);
}
}
3.知识点补充
@ConditionalOnClass
:当类路径上存在指定的类时创建Bean。@ConditionalOnMissingClass
:当类路径上不存在指定的类时创建Bean。@ConditionalOnProperty
:基于指定的配置属性是否存在及其值来创建Bean。@ConditionalOnBean
:当存在指定的Bean时创建Bean。@ConditionalOnMissingBean
:当不存在指定的Bean时创建Bean。@ConditionalOnResource
:当指定的资源存在时创建Bean
@Configuration public class MyConfiguration { @Bean @Conditional(MyCondition.class) public MyBean myBean() { return new MyBean(); } }
📝结束语:
总结不易😄觉得有用的话,还请各位大佬动动发财的小手
给小瞿扣个三连:⛳️ 点赞⭐️收藏 ❤️ 关注
这个对我真的非常重要,拜托啦!
本人水平有限,如有纰漏,欢迎各位大佬评论指正!💞