@yulongsun
2018-05-05T10:33:30.000000Z
字数 6999
阅读 1153
Dubbo源码走读
全称:Service Provider Interface.

//win.yulongsun.demo.spring.jdkspi.spi.HelloSPIInterfacepublic interface HelloSPIInterface {public void sayHello();}
//win.yulongsun.demo.spring.jdkspi.impl.HelloAImplpublic class HelloAImpl implements HelloSPIInterface {@Overridepublic void sayHello() {System.out.printf("say a");}}
//win.yulongsun.demo.spring.jdkspi.impl.HelloBImplpublic class HelloBImpl implements HelloSPIInterface{@Overridepublic void sayHello() {System.out.println("say b");}}
在classpath:META-INF/services/下新建
win.yulongsun.demo.spring.jdkspi.spi.HelloSPIInterface //=>全接口名称
内容为:
#具体实现类1win.yulongsun.demo.spring.jdkspi.impl.HelloAImpl#具体实现类2win.yulongsun.demo.spring.jdkspi.impl.HelloBImpl
public class HelloSPITestCase {public static void main(String[] args) {ServiceLoader<HelloSPIInterface> helloSPIInterfaces = ServiceLoader.load(HelloSPIInterface.class);for (HelloSPIInterface item : helloSPIInterfaces) {item.sayHello();}}}

SPI在查找具体实现的时候,会先遍历实例化所有实现,然后循环找需要的实现。实现了没有必要实现的实例;
//ServiceLoader实现了Iterable接口,可以遍历所有的服务实现者public final class ServiceLoader<S> implements Iterable<S>{//查找配置文件的目录private static final String PREFIX = "META-INF/services/";//表示要被加载的服务的类或接口private final Class<S> service;//这个ClassLoader用来定位,加载,实例化服务提供者private final ClassLoader loader;// 访问控制上下文private final AccessControlContext acc;// 缓存已经被实例化的服务提供者,按照实例化的顺序存储private LinkedHashMap<String,S> providers = new LinkedHashMap<>();// 迭代器private LazyIterator lookupIterator;//重新加载,就相当于重新创建ServiceLoader了,用于新的服务提供者安装到正在运行的Java虚拟机中的情况。public void reload() {//清空缓存中所有已实例化的服务提供者providers.clear();//新建一个迭代器,该迭代器会从头查找和实例化服务提供者lookupIterator = new LazyIterator(service, loader);}//私有构造器//使用指定的类加载器和服务创建服务加载器//如果没有指定类加载器,使用系统类加载器,就是应用类加载器。private ServiceLoader(Class<S> svc, ClassLoader cl) {service = Objects.requireNonNull(svc, "Service interface cannot be null");loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;reload();}//解析失败处理的方法private static void fail(Class<?> service, String msg, Throwable cause)throws ServiceConfigurationError{throw new ServiceConfigurationError(service.getName() + ": " + msg,cause);}private static void fail(Class<?> service, String msg)throws ServiceConfigurationError{throw new ServiceConfigurationError(service.getName() + ": " + msg);}private static void fail(Class<?> service, URL u, int line, String msg)throws ServiceConfigurationError{fail(service, u + ":" + line + ": " + msg);}//解析服务提供者配置文件中的一行//首先去掉注释校验,然后保存//返回下一行行号//重复的配置项和已经被实例化的配置项不会被保存private int parseLine(Class<?> service, URL u, BufferedReader r, int lc,List<String> names)throws IOException, ServiceConfigurationError{//读取一行String ln = r.readLine();if (ln == null) {return -1;}//#号代表注释行int ci = ln.indexOf('#');if (ci >= 0) ln = ln.substring(0, ci);ln = ln.trim();int n = ln.length();if (n != 0) {if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))fail(service, u, lc, "Illegal configuration-file syntax");int cp = ln.codePointAt(0);if (!Character.isJavaIdentifierStart(cp))fail(service, u, lc, "Illegal provider-class name: " + ln);for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {cp = ln.codePointAt(i);if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))fail(service, u, lc, "Illegal provider-class name: " + ln);}if (!providers.containsKey(ln) && !names.contains(ln))names.add(ln);}return lc + 1;}//解析配置文件,解析指定的url配置文件//使用parseLine方法进行解析,未被实例化的服务提供者会被保存到缓存中去private Iterator<String> parse(Class<?> service, URL u)throws ServiceConfigurationError{InputStream in = null;BufferedReader r = null;ArrayList<String> names = new ArrayList<>();try {in = u.openStream();r = new BufferedReader(new InputStreamReader(in, "utf-8"));int lc = 1;while ((lc = parseLine(service, u, r, lc, names)) >= 0);}return names.iterator();}//服务提供者查找的迭代器private class LazyIterator implements Iterator<S>{Class<S> service;//服务提供者接口ClassLoader loader;//类加载器Enumeration<URL> configs = null;//保存实现类的urlIterator<String> pending = null;//保存实现类的全名String nextName = null;//迭代器中下一个实现类的全名private LazyIterator(Class<S> service, ClassLoader loader) {this.service = service;this.loader = loader;}private boolean hasNextService() {if (nextName != null) {return true;}if (configs == null) {try {String fullName = PREFIX + service.getName();if (loader == null)configs = ClassLoader.getSystemResources(fullName);elseconfigs = loader.getResources(fullName);}}while ((pending == null) || !pending.hasNext()) {if (!configs.hasMoreElements()) {return false;}pending = parse(service, configs.nextElement());}nextName = pending.next();return true;}private S nextService() {if (!hasNextService())throw new NoSuchElementException();String cn = nextName;nextName = null;Class<?> c = null;try {c = Class.forName(cn, false, loader);}if (!service.isAssignableFrom(c)) {fail(service, "Provider " + cn + " not a subtype");}try {//注意:实例化S p = service.cast(c.newInstance());providers.put(cn, p);return p;}}public boolean hasNext() {if (acc == null) {return hasNextService();} else {PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {public Boolean run() { return hasNextService(); }};return AccessController.doPrivileged(action, acc);}}public S next() {if (acc == null) {return nextService();} else {PrivilegedAction<S> action = new PrivilegedAction<S>() {public S run() { return nextService(); }};return AccessController.doPrivileged(action, acc);}}public void remove() {throw new UnsupportedOperationException();}}//获取迭代器//返回遍历服务提供者的迭代器//以懒加载的方式加载可用的服务提供者//懒加载的实现是:解析配置文件和实例化服务提供者的工作由迭代器本身完成public Iterator<S> iterator() {return new Iterator<S>() {//按照实例化顺序返回已经缓存的服务提供者实例Iterator<Map.Entry<String,S>> knownProviders= providers.entrySet().iterator();public boolean hasNext() {if (knownProviders.hasNext())return true;return lookupIterator.hasNext();}public S next() {if (knownProviders.hasNext())return knownProviders.next().getValue();return lookupIterator.next();}public void remove() {throw new UnsupportedOperationException();}};}//为指定的服务使用指定的类加载器来创建一个ServiceLoaderpublic static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader){return new ServiceLoader<>(service, loader);}//使用线程上下文的类加载器来创建ServiceLoaderpublic static <S> ServiceLoader<S> load(Class<S> service) {ClassLoader cl = Thread.currentThread().getContextClassLoader();return ServiceLoader.load(service, cl);}//使用扩展类加载器为指定的服务创建ServiceLoader//只能找到并加载已经安装到当前Java虚拟机中的服务提供者,应用程序类路径中的服务提供者将被忽略public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {ClassLoader cl = ClassLoader.getSystemClassLoader();ClassLoader prev = null;while (cl != null) {prev = cl;cl = cl.getParent();}return ServiceLoader.load(service, prev);}public String toString() {return "java.util.ServiceLoader[" + service.getName() + "]";}}
1、Dubbo采用微内核+插件体系。使得扩展性强。
Dubbo强大的扩展能力,主要依赖于它自己实现的一套SPI机制,开发人员可以根据dubbo的规范进行扩展现有的功能或者替换现有的实现,dubbo内部的功能的实现也都是通过的SPI来实现的,这是dubbo的功能高度可插拔的原因。
2、SPI接口定义
public @interface SPI {/*** default extension name*/String value() default "";}
在扩展点加了@SPI注解,Dubbo会依次从以下目录加载具体实现:
META-INF/dubbo/internal/ --> Dubbo内部实现的各种插件META-INF/dubbo/META-INF/services/
3、特性
4、SPI使用
1、JDK SPI和Dubbo SPI有什么区别?
1、Dubbo SPI添加了缓存机制。增加了对IOC和AOP的支持。2、JDK SPI会一次性加载所有扩展点实现。
1、Dubbo原理解析-Dubbo内核实现之基于SPI思想Dubbo内核实现(转)
2、5.dubbo源码分析 之 SPI 分析
3、Dubbo扩展点加载机制 - ExtensionLoader