SPI机制中的SPI实现类的读取和预处理是由ExtensionLoader类的loadFile方法来完成的
loadFile方法的作用是读取dubbo的某个SPI接口的spi描述文件,然后进行缓存,缓存,缓存(很重要,说三遍) ,读取的位置是在jar包下的META-INF\dubbo\internal目录下
一. 先对loadFile方法进行下粗的了解:
- loadFile方法方法被调用的顺序如下:
getExtensionClasses() ——> loadExtensionClasses()——>loadFile()
2.loadFile方法的签名如下:
private void loadFile(Map<String, Class<?>> extensionClasses, String dir)
3. 方法的参数 extensionClasses
private Map<String, Class<?>> getExtensionClasses() {
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
if (classes == null) {
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
} private Map<String, Class<?>> loadExtensionClasses() {
final SPI defaultAnnotation = type.getAnnotation(SPI.class);
if(defaultAnnotation != null) {
String value = defaultAnnotation.value();
if(value != null && (value = value.trim()).length() > 0) {
String[] names = NAME_SEPARATOR.split(value);
if(names.length > 1) {
throw new IllegalStateException("more than 1 default extension name on extension " + type.getName()
+ ": " + Arrays.toString(names));
}
if(names.length == 1) cachedDefaultName = names[0];
}
} Map<String, Class<?>> extensionClasses = new HashMap<String, Class<?>>();
loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
loadFile(extensionClasses, DUBBO_DIRECTORY);
loadFile(extensionClasses, SERVICES_DIRECTORY);
return extensionClasses;
}
extensionClasses这个参数一看就知道会被loadFile方法在执行过程中填充,通过看调用链上的前两个方法的代码就能看出其作用 ,其实extensionClasses只是个临时变量,最终会保存在ExtensionLoader类的实例属性cachedClasses中 ,cachedClasses的定义和相关代码如下:
private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<Map<String,Class<?>>>(); /**
* Helper Class for hold a value.
*
* @author william.liangf
*/
public class Holder<T> { private volatile T value; public void set(T value) {
this.value = value;
} public T get() {
return value;
} }
二. 详细分析loadFile方法:
//通过传入type参数,即某个SPI接口的类路径全名,结合dubbo的spi机制定义的目录来确定要读取的spi描述文件
String fileName = dir + type.getName();
//读取文件中的每一行
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
line = reader.readLine()
//在JDK中加载每一行读到的类
Class<?> clazz = Class.forName(line, true, classLoader);
//要确保读到的每个类都是SPI接口的实现类
if (! type.isAssignableFrom(clazz)){
throw new IllegalStateException("Error when load extension class(interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + "is not subtype of interface.");
}
// 如果实现类上有Adaptive注解,则将读到的类赋值给ExtensionLoader类的实例属性cachedAdaptiveClass
if (clazz.isAnnotationPresent(Adaptive.class)) {
cachedAdaptiveClass = clazz;
}
else { //如果实现类上没有Adaptive注解,会做如下处理:
1. clazz.getConstructor(type); //如果这个带参的构造函数存在 , 则说明当前的读到的Class是有包装类的 ,则先将Class的类对象clazz放入ExtensionLoader类的实例属性 cachedWrapperClasses中
Set<Class<?>> wrappers = cachedWrapperClasses;
if (wrappers == null) {
cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
wrappers = cachedWrapperClasses;
}
wrappers.add(clazz);
//如果带参的构造函数不存在,则执行以下逻辑
2. clazz.getConstructor(); //获取不带参的构造函数
Activate activate = clazz.getAnnotation(Activate.class); //判断类上是否有Activate注解
if (activate != null) {
cachedActivates.put(names[0], activate); //如果Activate注解存在则放入到ExtensionLoader类的实例属性cachedActivates中
}
//以clazz为key,clazz的name为value缓存到ExtensionLoader类的实例属性cachedNames中
if (! cachedNames.containsKey(clazz)) {
cachedNames.put(clazz, n);
}
//以clazz的name为key,以clazz为value缓存到传入的参数extensionClasses中
Class<?> c = extensionClasses.get(n);
if (c == null) {
extensionClasses.put(n, clazz); //间接缓存到cachedClasses中
}
}
其实看源码分析的文章是有前提的,你必需自己要先去尽力去看过了。
总结:loadFile方法是ExtensionLoader类的私有方法,由于它不是static方法,所以调用时一定会有一个ExtensionLoader实例来调用这个方法的。所以它的作用就是每执行一次,它会去jar包下的META-INF\dubbo\internal目录下读取当前ExtensionLoader实例里的type属性对应的SPI接口的spi接口描述文件,也即是加载这个SPI接口对应的各个实现类。这个方法在执行过程中根据一些条件会做一些缓存的事。具体会影响到ExtensionLoader的下列属性:
cachedAdaptiveClass // private volatile Class<?> cachedAdaptiveClass = null;
cachedWrapperClasses //private Set<Class<?>> cachedWrapperClasses;
cachedActivates //private final Map<String, Activate> cachedActivates = new ConcurrentHashMap<String, Activate>();
cachedNames //private final ConcurrentMap<Class<?>, String> cachedNames = new ConcurrentHashMap<Class<?>, String>();
并间接影响了以下属性:
cachedClasses //private final Holder<Map<String, Class<?>>> cachedClasses = new Holder<Map<String,Class<?>>>();
以下是 loadFile方法的源码,也一并列上:
private void loadFile(Map<String, Class<?>> extensionClasses, String dir) {
String fileName = dir + type.getName();
try {
Enumeration<java.net.URL> urls;
ClassLoader classLoader = findClassLoader();
if (classLoader != null) {
urls = classLoader.getResources(fileName);
} else {
urls = ClassLoader.getSystemResources(fileName);
}
if (urls != null) {
while (urls.hasMoreElements()) {
java.net.URL url = urls.nextElement();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
try {
String line = null;
while ((line = reader.readLine()) != null) {
final int ci = line.indexOf('#');
if (ci >= 0) line = line.substring(0, ci);
line = line.trim();
if (line.length() > 0) {
try {
String name = null;
int i = line.indexOf('=');
if (i > 0) {
name = line.substring(0, i).trim();
line = line.substring(i + 1).trim();
}
if (line.length() > 0) {
Class<?> clazz = Class.forName(line, true, classLoader);
if (! type.isAssignableFrom(clazz)) {
throw new IllegalStateException("Error when load extension class(interface: " +
type + ", class line: " + clazz.getName() + "), class "
+ clazz.getName() + "is not subtype of interface.");
}
if (clazz.isAnnotationPresent(Adaptive.class)) {
if(cachedAdaptiveClass == null) {
cachedAdaptiveClass = clazz;
} else if (! cachedAdaptiveClass.equals(clazz)) {
throw new IllegalStateException("More than 1 adaptive class found: "
+ cachedAdaptiveClass.getClass().getName()
+ ", " + clazz.getClass().getName());
}
} else {
try {
clazz.getConstructor(type);
Set<Class<?>> wrappers = cachedWrapperClasses;
if (wrappers == null) {
cachedWrapperClasses = new ConcurrentHashSet<Class<?>>();
wrappers = cachedWrapperClasses;
}
wrappers.add(clazz);
} catch (NoSuchMethodException e) {
clazz.getConstructor();
if (name == null || name.length() == 0) {
name = findAnnotationName(clazz);
if (name == null || name.length() == 0) {
if (clazz.getSimpleName().length() > type.getSimpleName().length()
&& clazz.getSimpleName().endsWith(type.getSimpleName())) {
name = clazz.getSimpleName().substring(0, clazz.getSimpleName().length() - type.getSimpleName().length()).toLowerCase();
} else {
throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + url);
}
}
}
String[] names = NAME_SEPARATOR.split(name);
if (names != null && names.length > 0) {
Activate activate = clazz.getAnnotation(Activate.class);
if (activate != null) {
cachedActivates.put(names[0], activate);
}
for (String n : names) {
if (! cachedNames.containsKey(clazz)) {
cachedNames.put(clazz, n);
}
Class<?> c = extensionClasses.get(n);
if (c == null) {
extensionClasses.put(n, clazz);
} else if (c != clazz) {
throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName());
}
}
}
}
}
}
} catch (Throwable t) {
IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + url + ", cause: " + t.getMessage(), t);
exceptions.put(line, e);
}
}
} // end of while read lines
} finally {
reader.close();
}
} catch (Throwable t) {
logger.error("Exception when load extension class(interface: " +
type + ", class file: " + url + ") in " + url, t);
}
} // end of while urls
}
} catch (Throwable t) {
logger.error("Exception when load extension class(interface: " +
type + ", description file: " + fileName + ").", t);
}
}
总结:
1. loadFile方法的作用是读取各个SPI描述文件中的内容并作预处理
2. 缓存预处理的结果,缓存原则如下:
(1) 带Adaptive注解的实现类会被缓存在cachedAdaptiveClass上
(2) 其他的会被缓存在cachedClasses 上