聊聊如何实现一个带有拦截器功能的SPI

372 阅读3分钟

前言

上一篇文章我们聊了一下聊聊如何实现一个支持键值对的SPI。本期我们来聊聊如何实现一个带有拦截器功能的SPI

什么是拦截器

指在某个方法或字段被访问之前进行拦截,然后在之前或之后加入某些操作

什么是拦截器链

指将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用

实现拦截器逻辑

本文实现思路核心:利用责任链+动态代理

1、定义拦截器接口

public interface Interceptor {

  int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;

  int LOWEST_PRECEDENCE = Integer.MAX_VALUE;

  Object intercept(Invocation invocation) throws Throwable;

  default Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }


  int getOrder();

}

2、自定义需要被拦截器拦截的类接口注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
  Signature[] value();
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
  Class<?> type();

  String method();

  Class<?>[] args();
}

3、通过jdk动态代理实现拦截器调用逻辑

public class Plugin implements InvocationHandler {

  private final Object target;
  private final Interceptor interceptor;
  private final Map<Class<?>, Set<Method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        Invocation invocation = new Invocation(target, method, args);
        return interceptor.intercept(invocation);

      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtils.unwrapThrowable(e);
    }
  }

  private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
    }
    Signature[] sigs = interceptsAnnotation.value();
    Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
    for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
      try {
        Method method = sig.type().getMethod(sig.method(), sig.args());
        methods.add(method);
      } catch (NoSuchMethodException e) {
        throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
  }

  private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<>();
    while (type != null) {
      for (Class<?> c : type.getInterfaces()) {
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }

}

4、构造出拦截器链

public class InterceptorChain {

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


  public Object pluginAll(Object target) {
    if(CollectionUtil.isNotEmpty(interceptors)){
      for (Interceptor interceptor : getInterceptors()) {
         target = interceptor.plugin(target);
      }
    }

    return target;
  }

  public InterceptorChain addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
    return this;
  }

  public List<Interceptor> getInterceptors() {
    List<Interceptor> interceptorsByOrder = interceptors.stream().sorted(Comparator.comparing(Interceptor::getOrder).reversed()).collect(Collectors.toList());
    return Collections.unmodifiableList(interceptorsByOrder);
  }

}

5、通过拦截器链与之前实现的SPI绑定

@Activate
@Slf4j
public class InterceptorExtensionFactory implements ExtensionFactory {

    private InterceptorChain chain;


    @Override
    public <T> T getExtension(final String key, final Class<T> clazz) {
        if(Objects.isNull(chain)){
            log.warn("No InterceptorChain Is Config" );
            return null;
        }
        if (clazz.isInterface() && clazz.isAnnotationPresent(SPI.class)) {
            ExtensionLoader<T> extensionLoader = ExtensionLoader.getExtensionLoader(clazz);
            if (!extensionLoader.getSupportedExtensions().isEmpty()) {
               if(StringUtils.isBlank(key)){
                   return (T) chain.pluginAll(extensionLoader.getDefaultActivate());
               }
               return (T) chain.pluginAll(extensionLoader.getActivate(key));
            }
        }
        return null;
    }

    public InterceptorChain getChain() {
        return chain;
    }

    public InterceptorExtensionFactory setChain(InterceptorChain chain) {
        this.chain = chain;
        return this;
    }

示例演示

1、定义拦截器并指明要拦截的类接口方法

@Intercepts(@Signature(type = SqlDialect.class,method = "dialect",args = {}))
public class MysqlDialectInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("MysqlDialectInterceptor");
        return invocation.proceed();
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }


    @Override
    public Object plugin(Object target) {
        if(target.toString().startsWith(MysqlDialect.class.getName())){
            return Plugin.wrap(target,this);
        }
        return target;
    }
}

2、构造拦截器链并设置到spi工厂中

  @Before
    public void before(){
        InterceptorChain chain = new InterceptorChain();
        chain.addInterceptor(new DialectInterceptor()).addInterceptor(new MysqlDialectInterceptor()).addInterceptor(new OracleDialectInterceptor());
        factory = (InterceptorExtensionFactory) (ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getActivate("interceptor"));
        factory.setChain(chain);
    }

3、测试

    @Test
    public void testMysqlDialectInterceptor(){
        SqlDialect dialect = factory.getExtension("mysql",SqlDialect.class);
        Assert.assertEquals("mysql",dialect.dialect());
    }

从控制台输出就可以看出已经把拦截器调用逻辑实现出来

总结

看了本篇的拦截器实现,眼尖的朋友就会发现,你这不就是抄mybatis拦截器的实现。确实是这样,但我更愿意不要脸的称这个为学以致用。mybatis的拦截器实现确实挺巧妙的,因为我们常规实现拦截器链调用正常是使用类似递归的方式,mybatis却借助了动态代理。

当然本篇的拦截器也加了一点彩蛋,比如增加了原生mybatis拦截器没提供的自定义执行顺序功能,原生的mybatis拦截器只能拦截Executor、ParameterHandler 、StatementHandler 、ResultSetHandler。而本文则没这个限制,但有个注意点是因为拦截器实现是基于jdk动态代理,因此自定义注解的class只能指定为接口,而不能是具体实现

demo链接

github.com/lyb-geek/sp…