[关闭]
@yulongsun 2018-05-05T10:33:30.000000Z 字数 6999 阅读 1015

Dubbo源码走读 - Jdk SPI & Dubbo SPI

Dubbo源码走读


一、JDK SPI

1、jdk spi是什么?

全称:Service Provider Interface.

2、有什么作用?

3、使用demo

demo工程

3.1 定义标准接口

  1. //win.yulongsun.demo.spring.jdkspi.spi.HelloSPIInterface
  2. public interface HelloSPIInterface {
  3. public void sayHello();
  4. }

3.2 具体实现1

  1. //win.yulongsun.demo.spring.jdkspi.impl.HelloAImpl
  2. public class HelloAImpl implements HelloSPIInterface {
  3. @Override
  4. public void sayHello() {
  5. System.out.printf("say a");
  6. }
  7. }

3.3 具体实现2

  1. //win.yulongsun.demo.spring.jdkspi.impl.HelloBImpl
  2. public class HelloBImpl implements HelloSPIInterface{
  3. @Override
  4. public void sayHello() {
  5. System.out.println("say b");
  6. }
  7. }

3.4 配置<接口,实现类>

在classpath:META-INF/services/下新建

  1. win.yulongsun.demo.spring.jdkspi.spi.HelloSPIInterface //=>全接口名称

内容为:

  1. #具体实现类1
  2. win.yulongsun.demo.spring.jdkspi.impl.HelloAImpl
  3. #具体实现类2
  4. win.yulongsun.demo.spring.jdkspi.impl.HelloBImpl

3.5 测试

  1. public class HelloSPITestCase {
  2. public static void main(String[] args) {
  3. ServiceLoader<HelloSPIInterface> helloSPIInterfaces = ServiceLoader.load(HelloSPIInterface.class);
  4. for (HelloSPIInterface item : helloSPIInterfaces) {
  5. item.sayHello();
  6. }
  7. }
  8. }

测试结果

4、SPI的缺点

SPI在查找具体实现的时候,会先遍历实例化所有实现,然后循环找需要的实现。实现了没有必要实现的实例;

  1. //ServiceLoader实现了Iterable接口,可以遍历所有的服务实现者
  2. public final class ServiceLoader<S> implements Iterable<S>
  3. {
  4. //查找配置文件的目录
  5. private static final String PREFIX = "META-INF/services/";
  6. //表示要被加载的服务的类或接口
  7. private final Class<S> service;
  8. //这个ClassLoader用来定位,加载,实例化服务提供者
  9. private final ClassLoader loader;
  10. // 访问控制上下文
  11. private final AccessControlContext acc;
  12. // 缓存已经被实例化的服务提供者,按照实例化的顺序存储
  13. private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
  14. // 迭代器
  15. private LazyIterator lookupIterator;
  16. //重新加载,就相当于重新创建ServiceLoader了,用于新的服务提供者安装到正在运行的Java虚拟机中的情况。
  17. public void reload() {
  18. //清空缓存中所有已实例化的服务提供者
  19. providers.clear();
  20. //新建一个迭代器,该迭代器会从头查找和实例化服务提供者
  21. lookupIterator = new LazyIterator(service, loader);
  22. }
  23. //私有构造器
  24. //使用指定的类加载器和服务创建服务加载器
  25. //如果没有指定类加载器,使用系统类加载器,就是应用类加载器。
  26. private ServiceLoader(Class<S> svc, ClassLoader cl) {
  27. service = Objects.requireNonNull(svc, "Service interface cannot be null");
  28. loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
  29. acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
  30. reload();
  31. }
  32. //解析失败处理的方法
  33. private static void fail(Class<?> service, String msg, Throwable cause)
  34. throws ServiceConfigurationError
  35. {
  36. throw new ServiceConfigurationError(service.getName() + ": " + msg,cause);
  37. }
  38. private static void fail(Class<?> service, String msg)
  39. throws ServiceConfigurationError
  40. {
  41. throw new ServiceConfigurationError(service.getName() + ": " + msg);
  42. }
  43. private static void fail(Class<?> service, URL u, int line, String msg)
  44. throws ServiceConfigurationError
  45. {
  46. fail(service, u + ":" + line + ": " + msg);
  47. }
  48. //解析服务提供者配置文件中的一行
  49. //首先去掉注释校验,然后保存
  50. //返回下一行行号
  51. //重复的配置项和已经被实例化的配置项不会被保存
  52. private int parseLine(Class<?> service, URL u, BufferedReader r, int lc,
  53. List<String> names)
  54. throws IOException, ServiceConfigurationError
  55. {
  56. //读取一行
  57. String ln = r.readLine();
  58. if (ln == null) {
  59. return -1;
  60. }
  61. //#号代表注释行
  62. int ci = ln.indexOf('#');
  63. if (ci >= 0) ln = ln.substring(0, ci);
  64. ln = ln.trim();
  65. int n = ln.length();
  66. if (n != 0) {
  67. if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
  68. fail(service, u, lc, "Illegal configuration-file syntax");
  69. int cp = ln.codePointAt(0);
  70. if (!Character.isJavaIdentifierStart(cp))
  71. fail(service, u, lc, "Illegal provider-class name: " + ln);
  72. for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
  73. cp = ln.codePointAt(i);
  74. if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
  75. fail(service, u, lc, "Illegal provider-class name: " + ln);
  76. }
  77. if (!providers.containsKey(ln) && !names.contains(ln))
  78. names.add(ln);
  79. }
  80. return lc + 1;
  81. }
  82. //解析配置文件,解析指定的url配置文件
  83. //使用parseLine方法进行解析,未被实例化的服务提供者会被保存到缓存中去
  84. private Iterator<String> parse(Class<?> service, URL u)
  85. throws ServiceConfigurationError
  86. {
  87. InputStream in = null;
  88. BufferedReader r = null;
  89. ArrayList<String> names = new ArrayList<>();
  90. try {
  91. in = u.openStream();
  92. r = new BufferedReader(new InputStreamReader(in, "utf-8"));
  93. int lc = 1;
  94. while ((lc = parseLine(service, u, r, lc, names)) >= 0);
  95. }
  96. return names.iterator();
  97. }
  98. //服务提供者查找的迭代器
  99. private class LazyIterator implements Iterator<S>
  100. {
  101. Class<S> service;//服务提供者接口
  102. ClassLoader loader;//类加载器
  103. Enumeration<URL> configs = null;//保存实现类的url
  104. Iterator<String> pending = null;//保存实现类的全名
  105. String nextName = null;//迭代器中下一个实现类的全名
  106. private LazyIterator(Class<S> service, ClassLoader loader) {
  107. this.service = service;
  108. this.loader = loader;
  109. }
  110. private boolean hasNextService() {
  111. if (nextName != null) {
  112. return true;
  113. }
  114. if (configs == null) {
  115. try {
  116. String fullName = PREFIX + service.getName();
  117. if (loader == null)
  118. configs = ClassLoader.getSystemResources(fullName);
  119. else
  120. configs = loader.getResources(fullName);
  121. }
  122. }
  123. while ((pending == null) || !pending.hasNext()) {
  124. if (!configs.hasMoreElements()) {
  125. return false;
  126. }
  127. pending = parse(service, configs.nextElement());
  128. }
  129. nextName = pending.next();
  130. return true;
  131. }
  132. private S nextService() {
  133. if (!hasNextService())
  134. throw new NoSuchElementException();
  135. String cn = nextName;
  136. nextName = null;
  137. Class<?> c = null;
  138. try {
  139. c = Class.forName(cn, false, loader);
  140. }
  141. if (!service.isAssignableFrom(c)) {
  142. fail(service, "Provider " + cn + " not a subtype");
  143. }
  144. try {
  145. //注意:实例化
  146. S p = service.cast(c.newInstance());
  147. providers.put(cn, p);
  148. return p;
  149. }
  150. }
  151. public boolean hasNext() {
  152. if (acc == null) {
  153. return hasNextService();
  154. } else {
  155. PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
  156. public Boolean run() { return hasNextService(); }
  157. };
  158. return AccessController.doPrivileged(action, acc);
  159. }
  160. }
  161. public S next() {
  162. if (acc == null) {
  163. return nextService();
  164. } else {
  165. PrivilegedAction<S> action = new PrivilegedAction<S>() {
  166. public S run() { return nextService(); }
  167. };
  168. return AccessController.doPrivileged(action, acc);
  169. }
  170. }
  171. public void remove() {
  172. throw new UnsupportedOperationException();
  173. }
  174. }
  175. //获取迭代器
  176. //返回遍历服务提供者的迭代器
  177. //以懒加载的方式加载可用的服务提供者
  178. //懒加载的实现是:解析配置文件和实例化服务提供者的工作由迭代器本身完成
  179. public Iterator<S> iterator() {
  180. return new Iterator<S>() {
  181. //按照实例化顺序返回已经缓存的服务提供者实例
  182. Iterator<Map.Entry<String,S>> knownProviders
  183. = providers.entrySet().iterator();
  184. public boolean hasNext() {
  185. if (knownProviders.hasNext())
  186. return true;
  187. return lookupIterator.hasNext();
  188. }
  189. public S next() {
  190. if (knownProviders.hasNext())
  191. return knownProviders.next().getValue();
  192. return lookupIterator.next();
  193. }
  194. public void remove() {
  195. throw new UnsupportedOperationException();
  196. }
  197. };
  198. }
  199. //为指定的服务使用指定的类加载器来创建一个ServiceLoader
  200. public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader)
  201. {
  202. return new ServiceLoader<>(service, loader);
  203. }
  204. //使用线程上下文的类加载器来创建ServiceLoader
  205. public static <S> ServiceLoader<S> load(Class<S> service) {
  206. ClassLoader cl = Thread.currentThread().getContextClassLoader();
  207. return ServiceLoader.load(service, cl);
  208. }
  209. //使用扩展类加载器为指定的服务创建ServiceLoader
  210. //只能找到并加载已经安装到当前Java虚拟机中的服务提供者,应用程序类路径中的服务提供者将被忽略
  211. public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
  212. ClassLoader cl = ClassLoader.getSystemClassLoader();
  213. ClassLoader prev = null;
  214. while (cl != null) {
  215. prev = cl;
  216. cl = cl.getParent();
  217. }
  218. return ServiceLoader.load(service, prev);
  219. }
  220. public String toString() {
  221. return "java.util.ServiceLoader[" + service.getName() + "]";
  222. }
  223. }

二、Dubbo SPI内核加载

1、Dubbo采用微内核+插件体系。使得扩展性强。
Dubbo强大的扩展能力,主要依赖于它自己实现的一套SPI机制,开发人员可以根据dubbo的规范进行扩展现有的功能或者替换现有的实现,dubbo内部的功能的实现也都是通过的SPI来实现的,这是dubbo的功能高度可插拔的原因。

2、SPI接口定义

  1. public @interface SPI {
  2. /**
  3. * default extension name
  4. */
  5. String value() default "";
  6. }

在扩展点加了@SPI注解,Dubbo会依次从以下目录加载具体实现:

  1. META-INF/dubbo/internal/ --> Dubbo内部实现的各种插件
  2. META-INF/dubbo/
  3. META-INF/services/

3、特性

4、SPI使用


问题

1、JDK SPI和Dubbo SPI有什么区别?

  1. 1Dubbo SPI添加了缓存机制。增加了对IOCAOP的支持。
  2. 2JDK SPI会一次性加载所有扩展点实现。

参考

1、Dubbo原理解析-Dubbo内核实现之基于SPI思想Dubbo内核实现(转)
2、5.dubbo源码分析 之 SPI 分析
3、Dubbo扩展点加载机制 - ExtensionLoader

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注