dubbo extension扩展点 源代码

1.首先我们创建一些类,我们再一步一步的进行分析dubbo的扩展点的源代码

  

public class DefaultExtensionImpl implements MyInterface {

    @Override
    public String sayHello(String name, String type) {
        return this.getClass().getName() + "  " + name + "  " + type;
    }

}

public class ExtensionTest {

	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {
		System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		ExtensionLoader extensionLoader = ExtensionLoader
				.getExtensionLoader(MyInterface.class);
		MyInterface myFirstExtension = (MyInterface) extensionLoader
				.getAdaptiveExtension();
		System.out.println(myFirstExtension.sayHello("xxx",
				ExtensionType.defaults));
	}
}

public class ExtensionType {

	public static final String defaults = "defaults";

	public static final String other = "other";
}

@Adaptive
public class MyAdaptiveExtension implements MyInterface {
	@SuppressWarnings("rawtypes")
	@Override
	public String sayHello(String name, String type) {
		ExtensionLoader extensionLoader = ExtensionLoader
				.getExtensionLoader(MyInterface.class);
		MyInterface extension = (MyInterface) extensionLoader
				.getDefaultExtension();
		if (ExtensionType.defaults.equals(type)) {
			extension = (MyInterface) extensionLoader
					.getExtension("defaults");
		}
		if (ExtensionType.other.equals(type)) {
			extension = (MyInterface) extensionLoader
					.getExtension("other");
		}
		return extension.sayHello(name, type);
	}
}

@SPI("defaults")
public interface MyInterface {
	public String sayHello(String name, String type);
}

public class OtherExtensionImpl implements MyInterface {

	@Override
	public String sayHello(String name, String type) {
		return this.getClass().getName() + "  " + name + "  " + type;
	}

}


com.alibaba.dubbo.demo.extensiontest.MyInterface内容:

defaults=com.alibaba.dubbo.demo.extensiontest.DefaultExtensionImpl
other=com.alibaba.dubbo.demo.extensiontest.OtherExtensionImpl
adaptive=com.alibaba.dubbo.demo.extensiontest.MyAdaptiveExtension

运行的结果



2.现在需要创建一个ExtensionLoader对象 ,ExtensionLoader是个单例,但是提供了一个getExtensionLoader方法

@SuppressWarnings("unchecked")
	public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
		// 不能为空
		if (type == null)
			throw new IllegalArgumentException("Extension type == null");
		// 接口
		if (!type.isInterface()) {
			throw new IllegalArgumentException("Extension type(" + type
					+ ") is not interface!");
		}
		// spi类型
		if (!withExtensionAnnotation(type)) {
			throw new IllegalArgumentException("Extension type(" + type
					+ ") is not extension, because WITHOUT @"
					+ SPI.class.getSimpleName() + " Annotation!");
		}
		// 先从EXTENSION_LOADERS获取ExtensionLoader
		ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS
				.get(type);
		// 新建一个ExtensionLoader对象
		if (loader == null) {
			EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type));
			loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type);
		}
		return loader;
	}




3.创建一个ExtensionLoader对象

private ExtensionLoader(Class<?> type) {
        this.type = type;
         //如果type是ExtensionFactory.class返回null  如果不是的话 那么就创建一个type为ExtensionFactory.class的对象,之后再调用getAdaptiveExtension方法
        objectFactory = (type == ExtensionFactory.class ? null : ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension());
}

4.调用getAdaptiveExtension方法

@SuppressWarnings("unchecked")
    public T getAdaptiveExtension() {
        //先从cachedAdaptiveInstance(自适应的实现类,该类需要有@Adaptive注解)获取,不为null的话那么直接返回
        Object instance = cachedAdaptiveInstance.get(); 
        if (instance == null) {
            if(createAdaptiveInstanceError == null) {
                synchronized (cachedAdaptiveInstance) {
                    instance = cachedAdaptiveInstance.get();
                    if (instance == null) {
                        try {
                            //如果为null的话 调用createAdaptiveExtension方法
                            instance = createAdaptiveExtension();
                            //获取到实例之后,set到cachedAdaptiveInstance里
                            cachedAdaptiveInstance.set(instance);
                        } catch (Throwable t) {
                            createAdaptiveInstanceError = t;
                            throw new IllegalStateException("fail to create adaptive instance: " + t.toString(), t);
                        }
                    }
                }
            }
            else {
                throw new IllegalStateException("fail to create adaptive instance: " + createAdaptiveInstanceError.toString(), createAdaptiveInstanceError);
            }
        }

        return (T) instance;
    }
5.调用createAdaptiveExtension方法

@SuppressWarnings("unchecked")
    private T createAdaptiveExtension() {
        try {
            return injectExtension((T) getAdaptiveExtensionClass().newInstance());
        } catch (Exception e) {
            throw new IllegalStateException("Can not create adaptive extenstion " + type + ", cause: " + e.getMessage(), e);
        }
    }

6.调用getAdaptiveExtensionClass方法

private Class<?> getAdaptiveExtensionClass() {
        getExtensionClasses();        
        //如果cachedAdaptiveClass不为空 直接返回        
        if (cachedAdaptiveClass != null) {
            return cachedAdaptiveClass;
        }
        return cachedAdaptiveClass = createAdaptiveExtensionClass();
    }

7.调用getExtensionClasses方法

private Map<String, Class<?>> getExtensionClasses() {        
        //从cachedClasses获取        
        Map<String, Class<?>> classes = cachedClasses.get(); 
        if (classes == null) {
            synchronized (cachedClasses) {
                classes = cachedClasses.get();
                if (classes == null) {
                    //如果为null的话,开始进行读取配置文件
                    classes = loadExtensionClasses();
                    //放入到cachedClasses对象里
                    cachedClasses.set(classes);
                }
            }
        }
        return classes;
}

8.调用loadExtensionClasses方法

private Map<String, Class<?>> loadExtensionClasses() {
        final SPI defaultAnnotation = type.getAnnotation(SPI.class);
        if(defaultAnnotation != null) {
            String value = defaultAnnotation.value();
                //如果value不为空的话 赋值cachedDefaultName
                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<?>>();
        //读取配置文件META-INF/dubbo/internal/
        loadFile(extensionClasses, DUBBO_INTERNAL_DIRECTORY);
        //读取配置文件META-INF/dubbo/
        loadFile(extensionClasses, DUBBO_DIRECTORY);
        //读取配置文件META-INF/services/
        loadFile(extensionClasses, SERVICES_DIRECTORY);
        return extensionClasses;
    }

9.调用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.");
                                            }
                                            //判断该类是否是一个自适应的adaptive的类
                                            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);
        }
    }

10.创建AdaptiveExtensionFactory实例

    

@Adaptive
public class AdaptiveExtensionFactory implements ExtensionFactory {
    
    private final List<ExtensionFactory> factories;
    
    public AdaptiveExtensionFactory() {
        ExtensionLoader<ExtensionFactory> loader = ExtensionLoader.getExtensionLoader(ExtensionFactory.class);
        List<ExtensionFactory> list = new ArrayList<ExtensionFactory>();
        //loader.getSupportedExtensions() 获取extensions的实现类的key
        for (String name : loader.getSupportedExtensions()) {
             //获取extension的实现类
             list.add(loader.getExtension(name));
        }
        factories = Collections.unmodifiableList(list);
    }

    public <T> T getExtension(Class<T> type, String name) {
        for (ExtensionFactory factory : factories) {
            T extension = factory.getExtension(type, name);
            if (extension != null) {
                return extension;
            }
        }
        return null;
    }

}

11.调用getExtension方法

@SuppressWarnings("unchecked")
	public T getExtension(String name) {
		if (name == null || name.length() == 0)
		    throw new IllegalArgumentException("Extension name == null");
		if ("true".equals(name)) {
		    return getDefaultExtension();
		}
		Holder<Object> holder = cachedInstances.get(name);
                //cachedInstances通过name获取对象
                if (holder == null) {
                    //创建个新对象
                    cachedInstances.putIfAbsent(name, new Holder<Object>());
                    //放入cachedInstances对象里
                    holder = cachedInstances.get(name);
		}
		Object instance = holder.get();
		if (instance == null) {
		    synchronized (holder) {
	            instance = holder.get();
                    //如果holder的value里没有数据的话
                    if (instance == null) {
	                instance = createExtension(name);
	                holder.set(instance);
	            }
	        }
		}
		return (T) instance;
	}

12.调用createExtension方法

@SuppressWarnings("unchecked")
    private T createExtension(String name) {
        Class<?> clazz = getExtensionClasses().get(name);
        if (clazz == null) {
            throw findException(name);
        }
        try {
            //EXTENSION_INSTANCES里是否有实现类
            T instance = (T) EXTENSION_INSTANCES.get(clazz);
            //没有的话创建对象 赋值到EXTENSION_INSTANCES
            if (instance == null) {
                EXTENSION_INSTANCES.putIfAbsent(clazz, (T) clazz.newInstance());
                instance = (T) EXTENSION_INSTANCES.get(clazz);
            }
            //注入
            injectExtension(instance);
            //进行包装
            Set<Class<?>> wrapperClasses = cachedWrapperClasses;
            if (wrapperClasses != null && wrapperClasses.size() > 0) {
                for (Class<?> wrapperClass : wrapperClasses) {
                    instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
                }
            }
            return instance;
        } catch (Throwable t) {
            throw new IllegalStateException("Extension instance(name: " + name + ", class: " +
                    type + ")  could not be instantiated: " + t.getMessage(), t);
        }
    }

到此ExtensionLoader已经创建完成。

展开阅读全文

没有更多推荐了,返回首页