聊聊如何實現一個帶有攔截器功能的SPI

linyb極客之路發表於2021-10-26

前言

上一篇文章我們聊了一下聊聊如何實現一個支援鍵值對的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連結

https://github.com/lyb-geek/springboot-learning/tree/master/springboot-spi-enhance/springboot-spi-framework

相關文章