日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

很多情況我們系統要分析出來那些查詢很慢,其實可以通過MyBatis開發一個插件,去監控每次執行的sql耗時,如果超過配置的時間,則認為該sql屬于慢sql需要優化。日志里面就會打印每一個sql及相應的時間消耗

MyBatis插件-慢sql耗時監控插件

 

需要在mybatis.xml配置中<plugins>標簽下增加自己的插件代碼如下

<!-- SQL 執行性能分析,開發環境使用,線上不推薦。 maxTime 指的是 sql 最大執行時長 -->
<plugin interceptor="com.easy521.performance.SqlPerformanceInterceptor">
    <property name="maxTime" value="1000" /> 
</plugin>

最后附上SqlPerformanceInterceptor.JAVA攔截器代碼

/**
 * @author 郟高陽
 * @date 2020/4/29
 * @jdk.version 1.8
 * @desc mybatis執行sql性能分析插件
 */
package com.easy521.performance;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.Apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mApping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.defaults.DefaultSqlSession.StrictMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
@Intercepts({@Signature(
    type = StatementHandler.class,
    method = "query",
    args = {Statement.class, ResultHandler.class}
), @Signature(
    type = StatementHandler.class,
    method = "update",
    args = {Statement.class}
), @Signature(
    type = StatementHandler.class,
    method = "batch",
    args = {Statement.class}
)})
public class SqlPerformanceInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(SqlPerformanceInterceptor.class);
    private long maxTime = 1000L; // 最大耗時
    public SqlPerformanceInterceptor() {
    }
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        StatementHandler statementHandler = (StatementHandler)target;
        long start = SystemClock.now();
        Object result = invocation.proceed();
        long sqlCost = SystemClock.now() - start;
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
        sql = this.formatSql(sql, parameterObject, parameterMappingList);
        if (sqlCost < this.maxTime) {
            logger.info("SQL:{}  執行耗時:{}ms", sql, sqlCost);
        } else {
            logger.info("SQL:{}  執行耗時:{}ms  超過最大執行時間", sql, sqlCost);
        }
        return result;
    }
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    public void setProperties(Properties properties) {
        String maxTime = properties.getProperty("maxTime");
        if (!StringUtils.isEmpty(maxTime)) {
            this.maxTime = Long.parseLong(maxTime);
        }
    }
    private String formatSql(String sql, Object parameterObject, List<ParameterMapping> parameterMappingList) {
        if (sql != null && sql.length() != 0) {
            sql = this.beautifySql(sql);
            if (parameterObject != null && parameterMappingList != null && parameterMappingList.size() != 0) {
                try {
                    if (parameterMappingList != null) {
                        Class<?> parameterObjectClass = parameterObject.getClass();
                        if (this.isStrictMap(parameterObjectClass)) {
                            StrictMap<Collection<?>> strictMap = (StrictMap)parameterObject;
                            if (this.isList(((Collection)strictMap.get("list")).getClass())) {
                                sql = this.handleListParameter(sql, (Collection)strictMap.get("list"));
                            }
                        } else if (this.isMap(parameterObjectClass)) {
                            Map<?, ?> paramMap = (Map)parameterObject;
                            sql = this.handleMapParameter(sql, paramMap, parameterMappingList);
                        } else {
                            sql = this.handleCommonParameter(sql, parameterMappingList, parameterObjectClass, parameterObject);
                        }
                    }
                    return sql;
                } catch (Exception var7) {
                    return sql;
                }
            } else {
                return sql;
            }
        } else {
            return "";
        }
    }
    private String beautifySql(String sql) {
        sql = sql.replaceAll("[\sn ]+", " ");
        return sql;
    }
    private String handleListParameter(String sql, Collection<?> col) {
        String value;
        if (col != null && col.size() != 0) {
            for(Iterator var3 = col.iterator(); var3.hasNext(); sql = sql.replaceFirst("\?", value)) {
                Object obj = var3.next();
                value = null;
                Class<?> objClass = obj.getClass();
                if (this.isPrimitiveOrPrimitiveWrapper(objClass)) {
                    value = obj.toString();
                } else if (objClass.isAssignableFrom(String.class)) {
                    value = """ + obj.toString() + """;
                }
            }
        }
        return sql;
    }
    private String handleMapParameter(String sql, Map<?, ?> paramMap, List<ParameterMapping> parameterMappingList) {
        Iterator var4 = parameterMappingList.iterator();
        while(var4.hasNext()) {
            ParameterMapping parameterMapping = (ParameterMapping)var4.next();
            Object propertyName = parameterMapping.getProperty();
            Object propertyValue = paramMap.get(propertyName);
            if (propertyValue != null) {
                if (propertyValue.getClass().isAssignableFrom(String.class)) {
                    propertyValue = """ + propertyValue + """;
                }
                sql = sql.replaceFirst("\?", propertyValue.toString());
            }
        }
        return sql;
    }
    private String handleCommonParameter(String sql, List<ParameterMapping> parameterMappingList, Class<?> parameterObjectClass, Object parameterObject) throws Exception {
        String propertyValue;
        for(Iterator var5 = parameterMappingList.iterator(); var5.hasNext(); sql = sql.replaceFirst("\?", propertyValue)) {
            ParameterMapping parameterMapping = (ParameterMapping)var5.next();
            propertyValue = null;
            if (this.isPrimitiveOrPrimitiveWrapper(parameterObjectClass)) {
                propertyValue = parameterObject.toString();
            } else {
                String propertyName = parameterMapping.getProperty();
                Field field = parameterObjectClass.getDeclaredField(propertyName);
                field.setAccessible(true);
                propertyValue = String.valueOf(field.get(parameterObject));
                if (parameterMapping.getJavaType().isAssignableFrom(String.class)) {
                    propertyValue = """ + propertyValue + """;
                }
            }
        }
        return sql;
    }
    private boolean isPrimitiveOrPrimitiveWrapper(Class<?> parameterObjectClass) {
        return parameterObjectClass.isPrimitive() || parameterObjectClass.isAssignableFrom(Byte.class) || parameterObjectClass.isAssignableFrom(Short.class) || parameterObjectClass.isAssignableFrom(Integer.class) || parameterObjectClass.isAssignableFrom(Long.class) || parameterObjectClass.isAssignableFrom(Double.class) || parameterObjectClass.isAssignableFrom(Float.class) || parameterObjectClass.isAssignableFrom(Character.class) || parameterObjectClass.isAssignableFrom(Boolean.class);
    }
    private boolean isStrictMap(Class<?> parameterObjectClass) {
        return parameterObjectClass.isAssignableFrom(StrictMap.class);
    }
    private boolean isList(Class<?> clazz) {
        Class<?>[] interfaceClasses = clazz.getInterfaces();
        Class[] var3 = interfaceClasses;
        int var4 = interfaceClasses.length;
        for(int var5 = 0; var5 < var4; ++var5) {
            Class<?> interfaceClass = var3[var5];
            if (interfaceClass.isAssignableFrom(List.class)) {
                return true;
            }
        }
        return false;
    }
    private boolean isMap(Class<?> parameterObjectClass) {
        Class<?>[] interfaceClasses = parameterObjectClass.getInterfaces();
        Class[] var3 = interfaceClasses;
        int var4 = interfaceClasses.length;
        for(int var5 = 0; var5 < var4; ++var5) {
            Class<?> interfaceClass = var3[var5];
            if (interfaceClass.isAssignableFrom(Map.class)) {
                return true;
            }
        }
        return false;
    }
    public long getMaxTime() {
        return this.maxTime;
    }
    public void setMaxTime(long maxTime) {
        this.maxTime = maxTime;
    }
}

分享到:
標簽:插件 MyBatis
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定