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

32次阅读

共计 5728 个字符,预计需要花费 15 分钟才能阅读完成。

前言

上一篇文章咱们聊了一下聊聊如何实现一个反对键值对的 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

正文完
 0