自动化立体仓库 - WMS系统
pjb
1 天以前 05d9fd6f29e17ba0b118443d62bf873b37ee37e4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.zy.common.config;
/**
 * @author pang.jiabao
 * @description 记录慢sql日志
 * @createDate 2024/10/25 16:18
 */
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.util.Properties;
 
@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})
})
public class SlowSqlInterceptor implements Interceptor {
 
    private static final Logger logger = LoggerFactory.getLogger(com.zy.common.config.SlowSqlInterceptor.class);
 
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        String sqlId = ms.getId(); // 获取 SQL ID
        // 获取 SQL 语句,可以用 sqlSource
        String sql = ms.getBoundSql(invocation.getArgs()[1]).getSql(); // 获取具体的 SQL 语句
 
        long startTime = System.currentTimeMillis();
        Object result = invocation.proceed();
        long duration = System.currentTimeMillis() - startTime;
 
        if (duration > 500) { // 阈值
            logger.warn("慢SQL: {},执行时间: {}毫秒,具体SQL: {}", sqlId, duration, sql);
        }
 
        return result;
    }
 
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }
 
    @Override
    public void setProperties(Properties properties) {
 
    }
}