package com.example.spring_boot_demo.utils.aop; import com.example.spring_boot_demo.utils.redis.MybatisSqlInterceptorRedisUtils; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.type.TypeHandlerRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.lang.reflect.Field; import java.sql.Statement; import java.text.DateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Properties; @Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})}) @Component @Slf4j public class MybatisSqlInterceptor implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { long startTime = System.currentTimeMillis(); Object target = invocation.getTarget(); String outputString = ""; String sql = ""; try { StatementHandler statementHandler = (StatementHandler) target; BoundSql boundSql = statementHandler.getBoundSql(); //MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler); sql = boundSql.getSql(); if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) { ParameterMapping parameterMapping = boundSql.getParameterMappings().get(0); Field field = parameterMapping.getClass().getDeclaredField("configuration"); field.setAccessible(true); Configuration config = (Configuration) field.get(parameterMapping); //格式化Sql语句,去除换行符,替换参数 sql = showSql(config, boundSql); } else { sql = sql.replaceAll("[\\s]+", " "); } //日志 outputString += ("sql|" + sql); } catch (Exception e) { log.error("get sql1 error:" + e.getMessage(), e); } Object result = invocation.proceed(); try { return result; } finally { long endTime = System.currentTimeMillis(); long sqlCost = endTime - startTime; //计算结果 int total = 0; if (result != null && result instanceof List) { total = ((List) result).size(); } else if (result != null) { total = 1; } try { outputString += ("|time:" + sqlCost + "ms|total:" + total); } catch (Exception e) { log.error("get sql2 error:" + e.getMessage(), e); } log.info(outputString); } } public Object plugin(Object o) { return Plugin.wrap(o, this); } public void setProperties(Properties properties) { } public String showSql(Configuration configuration, BoundSql boundSql) { Object parameterObject = boundSql.getParameterObject(); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); String sql = boundSql.getSql().replaceAll("[\\s]+", " "); if (parameterMappings.size() > 0 && parameterObject != null) { TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { if (!sql.contains("?")) { return sql; } sql = sql.replaceFirst("\\?", getParameterValue(parameterObject)); } else { MetaObject metaObject = configuration.newMetaObject(parameterObject); for (ParameterMapping parameterMapping : parameterMappings) { if (!sql.contains("?")) { continue; } String propertyName = parameterMapping.getProperty(); if (metaObject.hasGetter(propertyName)) { Object obj = metaObject.getValue(propertyName); sql = sql.replaceFirst("\\?", getParameterValue(obj)); } else if (boundSql.hasAdditionalParameter(propertyName)) { Object obj = boundSql.getAdditionalParameter(propertyName); sql = sql.replaceFirst("\\?", getParameterValue(obj)); } } } } return sql; } private static String getParameterValue(Object obj) { String value = null; if (obj instanceof String) { value = "'" + obj.toString() + "'"; } else if (obj instanceof Date) { DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA); value = "'" + formatter.format(new Date()) + "'"; } else { if (obj != null) { value = obj.toString(); } else { value = " null "; } } // 转译特殊字符 if ((value.indexOf('\\') > -1) || (value.indexOf('$') > -1)) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c == '\\' || c == '$') { sb.append('\\'); } sb.append(c); } value = sb.toString(); } return value; } }