本文主要研究一下dubbo的ClassLoaderFilter

ClassLoaderFilter

dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/filter/ClassLoaderFilter.java

@Activate(group = CommonConstants.PROVIDER, order = -30000)
public class ClassLoaderFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        ClassLoader ocl = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(invoker.getInterface().getClassLoader());
        try {
            return invoker.invoke(invocation);
        } finally {
            Thread.currentThread().setContextClassLoader(ocl);
        }
    }

}
  • ClassLoaderFilter实现了Filter接口,其invoke方法首先获取当前线程的contextClassLoader,然后将其ContextClassLoader设置为invoker.getInterface().getClassLoader(),之后执行invoker.invoke方法,最后将当前线程的classLoader重置为原来的contextClassLoader

实例

dubbo-2.7.2/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.java

public class ClassLoaderFilterTest {

    private ClassLoaderFilter classLoaderFilter = new ClassLoaderFilter();

    @Test
    public void testInvoke() throws Exception {
        URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1");

        String path = DemoService.class.getResource("/").getPath();
        final URLClassLoader cl = new URLClassLoader(new java.net.URL[]{new java.net.URL("file:" + path)}) {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    return findClass(name);
                } catch (ClassNotFoundException e) {
                    return super.loadClass(name);
                }
            }
        };
        final Class<?> clazz = cl.loadClass(DemoService.class.getCanonicalName());
        Invoker invoker = new MyInvoker(url) {
            @Override
            public Class getInterface() {
                return clazz;
            }

            @Override
            public Result invoke(Invocation invocation) throws RpcException {
                Assertions.assertEquals(cl, Thread.currentThread().getContextClassLoader());
                return null;
            }
        };
        Invocation invocation = Mockito.mock(Invocation.class);

        classLoaderFilter.invoke(invoker, invocation);
    }
}
  • 这里invoker的interface设置为DemoService.class,然后验证invoke方法里头的Thread.currentThread().getContextClassLoader()为加载DemoService.class的URLClassLoader

小结

ClassLoaderFilter实现了Filter接口,其invoke方法首先获取当前线程的contextClassLoader,然后将其ContextClassLoader设置为invoker.getInterface().getClassLoader(),之后执行invoker.invoke方法,最后将当前线程的classLoader重置为原来的contextClassLoader

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...


引用和评论

0 条评论