tech.mhuang.pacebox.springboot.autoconfiguration.trace.mybatis.TraceMybatisInterceptor Maven / Gradle / Ivy
package tech.mhuang.pacebox.springboot.autoconfiguration.trace.mybatis;
import com.alibaba.fastjson2.JSON;
import com.zaxxer.hikari.HikariDataSource;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
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.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.dict.BasicDict;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.autoconfiguration.trace.annoation.IgnoreTrace;
import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
/**
* mybatis配置
*
* @author mhuang
* @since 1.0.0
*/
@Slf4j
@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 TraceMybatisInterceptor implements Interceptor {
private final Tracer tracer;
public TraceMybatisInterceptor(Tracer tracer) {
this.tracer = tracer;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
if (ObjectUtil.isNotEmpty(tracer.currentTraceContext())) {
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
String id = ms.getId();
int indexOf = id.lastIndexOf(".");
Class clazz = Class.forName(id.substring(0, indexOf));
String methodName = id.substring(indexOf + 1);
for (Method method : clazz.getDeclaredMethods()) {
if (StringUtil.equals(method.getName(), methodName)) {
IgnoreTrace ignoreTrace = method.getAnnotation(IgnoreTrace.class);
if (ignoreTrace == null) {
break;
}
return invocation.proceed();
}
}
Span span = tracer.nextSpan().name("sql");
try (Tracer.SpanInScope ws = this.tracer.withSpan(span.start())) {
BoundSql boundSql = ms.getBoundSql(objects[1]);
DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource();
if (dataSource instanceof HikariDataSource hikariDataSource) {
span.tag("db.instance", hikariDataSource.getJdbcUrl());
span.tag("db.user", hikariDataSource.getUsername());
}
BasicDict sqlDict = showSql(ms.getConfiguration(), boundSql);
span.tag("db.statement", sqlDict.get("sql", String.class));
span.tag("db.params", JSON.toJSONString(sqlDict.getOrDefault("params", "")));
Object proceed = invocation.proceed();
span.tag("db.result", JSON.toJSONString(proceed));
span.event("sqlEnd");
return proceed;
} catch (Exception e) {
span.error(e);
throw e;
} finally {
span.end();
}
}
return invocation.proceed();
}
private static String getParameterValue(Object obj) {
String value;
if (obj instanceof String) {
value = "'" + obj + "'";
} else if (obj instanceof Date) {
value = "'" + DateTimeUtil.fromDateTime(LocalDateTime.now()) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
}
public static BasicDict showSql(Configuration configuration, BoundSql boundSql) {
BasicDict basicDict = new BasicDict();
// 获取参数
Object parameterObject = boundSql.getParameterObject();
List parameterMappings = boundSql
.getParameterMappings();
// sql语句中多个空格都用一个空格代替
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
BasicDict paramDict = new BasicDict();
if (CollectionUtil.isNotEmpty(parameterMappings) && parameterObject != null) {
// 获取类型处理器注册器,类型处理器的功能是进行java类型和数据库类型的转换
// 如果根据parameterObject.getClass()可以找到对应的类型,则替换
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
String paramValue = Matcher.quoteReplacement(getParameterValue(parameterObject));
paramDict.set(parameterMappings.get(0).getProperty(), paramValue);
sql = sql.replaceFirst("\\?", paramValue);
} else {
// MetaObject主要是封装了originalObject对象,提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
String paramValue = Matcher.quoteReplacement(getParameterValue(obj));
paramDict.set(propertyName, paramValue);
sql = sql.replaceFirst("\\?", paramValue);
} else if (boundSql.hasAdditionalParameter(propertyName)) {
// 该分支是动态sql
Object obj = boundSql.getAdditionalParameter(propertyName);
String paramValue = Matcher.quoteReplacement(getParameterValue(obj));
paramDict.set(propertyName, paramValue);
sql = sql.replaceFirst("\\?", paramValue);
} else {
sql = sql.replaceFirst("\\?", "缺失");
}
//打印出缺失,提醒该参数缺失并防止错位
}
}
}
basicDict.set("sql", sql);
basicDict.set("params", paramDict);
return basicDict;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}