共计 2173 个字符,预计需要花费 6 分钟才能阅读完成。
序
本文主要研究一下 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
- ClassLoaderFilter
正文完