前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >聊聊如何实现一个带有拦截器功能的SPI

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

作者头像
lyb-geek
发布2022-01-07 10:05:51
4110
发布2022-01-07 10:05:51
举报
文章被收录于专栏:Linyb极客之路

01

前言

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

什么是拦截器

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

什么是拦截器链

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

02

实现拦截器逻辑

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

01

定义拦截器接口

代码语言:javascript
复制
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();

}

02

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

代码语言:javascript
复制
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
  Signature[] value();
}
代码语言:javascript
复制
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Signature {
  Class<?> type();

  String method();

  Class<?>[] args();
}

03

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

代码语言:javascript
复制
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()]);
  }

}

04

构造出拦截器链

代码语言:javascript
复制
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);
  }

}

05

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

代码语言:javascript
复制
@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;
    }

03

示例演示

01

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

代码语言:javascript
复制
@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;
    }
}

02

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

代码语言:javascript
复制
@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);
    }

03

测试

代码语言:javascript
复制
@Test
    public void testMysqlDialectInterceptor(){
        SqlDialect dialect = factory.getExtension("mysql",SqlDialect.class);
        Assert.assertEquals("mysql",dialect.dialect());
    }

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

04

总结

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

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

05

demo链接

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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-10-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Linyb极客之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档