Mybatis插件原理与实战案例分享

本文主要会结合源码来分析mybatis插件的实现原理,然后再通过案例帮助我们更好的进行理解。

首先看一下插件是如何被扫描到的

要想在mybatis中使用插件,必须要先在配置文件进行配置,参考如下。

<plugins>
	<plugin interceptor="com.mybatis.interceptors.SlowSqlInterceptor">
		<property name="slowSqlTime" value="1"/>
	</plugin>
</plugins>

然后在mybatis初始化时会扫描并处理plugins标签,由XMLConfigBuilder类中的方法负责处理,包含了配置中各个标签的解析。

private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      //解析plugins标签
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }
private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
    遍历所有的插件
      for (XNode child : parent.getChildren()) {
      //获取插件类的全限定名:com.mybatis.interceptors.SlowSqlInterceptor
        String interceptor = child.getStringAttribute("interceptor");
        //获取插件的配置属性:<property name="threshold" value="1"/>
        Properties properties = child.getChildrenAsProperties();
        //实例化
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
        //设置属性
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }
public void addInterceptor(Interceptor interceptor) {
	//调用InterceptorChain的addInterceptor方法
    interceptorChain.addInterceptor(interceptor);
  }
public class InterceptorChain {

  private final List<Interceptor> interceptors = new ArrayList<>();

  public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }
  
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }

}

最终可以得出,mybaits在初始化时会把配置文件中的类先进行实例化,然后添加到一个list容器中,容器中存放的都是Interceptor的实现类。

哪些方法执行的过程中可以被插件拦截?

mybaits中在执行一段sql调用时,一共有4个阶段可以进行拦截,分别是Executor、ParameterHandler 、StatementHandler 、ResultSetHandler ,每个阶段都是调用了InterceptorChain中的pluginAll方法,将需要被拦截的目标类传入,通过代理增加插件功能。

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
    parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
    return parameterHandler;
  }
 
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
      ResultHandler resultHandler, BoundSql boundSql) {
    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
  }
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }

如何为目标类增强插件功能?

现在我们知道4个可以被拦截的地方,都调用了interceptorChain的pluginAll方法。
pluginAll方法遍历了所有初始化时从配置文件中找到类,依次进行处理。

public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }
@Override
public Object plugin(Object target) {
	return Plugin.wrap(target, this);
}

//生成动态代理的方法
public static Object wrap(Object target, Interceptor interceptor) {
	//解析SlowSqlInterceptor上@Intercepts注解得到signature信息
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    //根据signatureMap 获取可以拦截的接口
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
    	//通过jdk动态代理方式生成代理
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

//通过jdk动态代理生成的代理类,执行方法时必然会调用到invoke方法
@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
    //获取当前可以被拦截的接口
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      //判断当前方法是否可以被拦截,如果可以则调用intercept,这个方法是我们自己实现的具体拦截的业务方法
      if (methods != null && methods.contains(method)) {
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //如果不可以则直接调用自身方法
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

从源码可以看出插件拦截的主要逻辑就是,先通过遍历的所有插件的方式,依次解析插件类上@Signature注解的属性,然后为被拦截的对象(上述的4大类)通过JDK动态代理的方式生成代理类,之后在sql调用的时候,就会判断当前方法是否可以被拦截,如果可以则调用拦截方法否则直接调用自身方法返回。

实战案例分享

利用mybatis插件的方式,实现慢sql的监控。

配置文件中加入

<plugins>
	<plugin interceptor="com.mybatis.interceptors.SlowSqlInterceptor">
		//设置超过10毫秒即为慢sql
		<property name="slowSqlTime" value="10"/>
	</plugin>
</plugins>

插件类,实现Interceptor接口

@Intercepts({
        @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})
})
public class SlowSqlInterceptor implements Interceptor {

    private long slowSqlTime;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long start = System.currentTimeMillis();
        Object object = invocation.proceed();
        long end = System.currentTimeMillis();
        long countTime = end - start;
        if (countTime >= slowSqlTime) {
            Object[] args = invocation.getArgs();
            Statement statement = (Statement) args[0];
            MetaObject metaObjectStat = SystemMetaObject.forObject(statement);
            PreparedStatementLogger statementLogger = (PreparedStatementLogger) metaObjectStat.getValue("h");
            Statement preparedStatement = statementLogger.getPreparedStatement();
            System.out.println("当前sql:" + preparedStatement.toString() + ",执行时间为:" + countTime + "毫秒,监控为慢sql!");
        }
        return object;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.slowSqlTime = Long.valueOf(properties.getProperty("slowSqlTime"));
    }
}
当前sql:com.mysql.jdbc.JDBC4PreparedStatement@15eb5ee5: select
		id, userName
		from t_user
		where id = 2,执行时间为:12毫秒,监控为慢sql!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码拉松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值