Dubbo源码分析(三):Dubbo之服务端(Service)

    

    如上图所示的Dubbo的暴露服务的过程,不难看出它也和消费者端很像,也需要一个像reference的对象来维护service关联的所有对象及其属性,这里的reference就是provider。由于ServiceBean实现了



InitializingBean接口,所有在Spring实例化这个bean后会调用接口方法afterPropertiesSet:

 
  1. public void afterPropertiesSet() throws Exception {

  2. //如果没有配置provider

  3. if (getProvider() == null) {

  4. //获取IOC容器里的所有provider

  5. Map<String, ProviderConfig> providerConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProviderConfig.class, false, false);

  6. if (providerConfigMap != null && providerConfigMap.size() > 0) {

  7. Map<String, ProtocolConfig> protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false);

  8. if ((protocolConfigMap == null || protocolConfigMap.size() == 0)

  9. && providerConfigMap.size() > 1) { // 兼容旧版本

  10. List<ProviderConfig> providerConfigs = new ArrayList<ProviderConfig>();

  11. for (ProviderConfig config : providerConfigMap.values()) {

  12. if (config.isDefault() != null && config.isDefault().booleanValue()) {

  13. providerConfigs.add(config);

  14. }

  15. }

  16. //关联所有providers

  17. if (providerConfigs.size() > 0) {

  18. setProviders(providerConfigs);

  19. }

  20. } else {

  21. ProviderConfig providerConfig = null;

  22. for (ProviderConfig config : providerConfigMap.values()) {

  23. if (config.isDefault() == null || config.isDefault().booleanValue()) {

  24. if (providerConfig != null) {

  25. throw new IllegalStateException("Duplicate provider configs: " + providerConfig + " and " + config);

  26. }

  27. providerConfig = config;

  28. }

  29. }

  30. if (providerConfig != null) {

  31. setProvider(providerConfig);

  32. }

  33. }

  34. }

  35. }

  36. //如果没有配置application,且没有配置provider

  37. if (getApplication() == null

  38. && (getProvider() == null || getProvider().getApplication() == null)) {

  39. //获取所有applications

  40. Map<String, ApplicationConfig> applicationConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ApplicationConfig.class, false, false);

  41. if (applicationConfigMap != null && applicationConfigMap.size() > 0) {

  42. ApplicationConfig applicationConfig = null;

  43. for (ApplicationConfig config : applicationConfigMap.values()) {

  44. if (config.isDefault() == null || config.isDefault().booleanValue()) {

  45. if (applicationConfig != null) {

  46. throw new IllegalStateException("Duplicate application configs: " + applicationConfig + " and " + config);

  47. }

  48. applicationConfig = config;

  49. }

  50. }

  51. //关联application

  52. if (applicationConfig != null) {

  53. setApplication(applicationConfig);

  54. }

  55. }

  56. }

  57. //如果没有配置module,且没有配置provider

  58. if (getModule() == null

  59. && (getProvider() == null || getProvider().getModule() == null)) {

  60. Map<String, ModuleConfig> moduleConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ModuleConfig.class, false, false);

  61. if (moduleConfigMap != null && moduleConfigMap.size() > 0) {

  62. ModuleConfig moduleConfig = null;

  63. for (ModuleConfig config : moduleConfigMap.values()) {

  64. if (config.isDefault() == null || config.isDefault().booleanValue()) {

  65. if (moduleConfig != null) {

  66. throw new IllegalStateException("Duplicate module configs: " + moduleConfig + " and " + config);

  67. }

  68. moduleConfig = config;

  69. }

  70. }

  71. //关联module

  72. if (moduleConfig != null) {

  73. setModule(moduleConfig);

  74. }

  75. }

  76. }

  77. //如果没有配置registries,且没有配置provider

  78. if ((getRegistries() == null || getRegistries().size() == 0)

  79. && (getProvider() == null || getProvider().getRegistries() == null || getProvider().getRegistries().size() == 0)

  80. && (getApplication() == null || getApplication().getRegistries() == null || getApplication().getRegistries().size() == 0)) {

  81. Map<String, RegistryConfig> registryConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, RegistryConfig.class, false, false);

  82. if (registryConfigMap != null && registryConfigMap.size() > 0) {

  83. List<RegistryConfig> registryConfigs = new ArrayList<RegistryConfig>();

  84. for (RegistryConfig config : registryConfigMap.values()) {

  85. if (config.isDefault() == null || config.isDefault().booleanValue()) {

  86. registryConfigs.add(config);

  87. }

  88. }

  89. //关联registries

  90. if (registryConfigs != null && registryConfigs.size() > 0) {

  91. super.setRegistries(registryConfigs);

  92. }

  93. }

  94. }

  95. //如果没有配置monitor,且没有配置provider

  96. if (getMonitor() == null

  97. && (getProvider() == null || getProvider().getMonitor() == null)

  98. && (getApplication() == null || getApplication().getMonitor() == null)) {

  99. Map<String, MonitorConfig> monitorConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, MonitorConfig.class, false, false);

  100. if (monitorConfigMap != null && monitorConfigMap.size() > 0) {

  101. MonitorConfig monitorConfig = null;

  102. for (MonitorConfig config : monitorConfigMap.values()) {

  103. if (config.isDefault() == null || config.isDefault().booleanValue()) {

  104. if (monitorConfig != null) {

  105. throw new IllegalStateException("Duplicate monitor configs: " + monitorConfig + " and " + config);

  106. }

  107. monitorConfig = config;

  108. }

  109. }

  110. //关联monitor

  111. if (monitorConfig != null) {

  112. setMonitor(monitorConfig);

  113. }

  114. }

  115. }

  116. //如果没有配置protocol,且没有配置provider

  117. if ((getProtocols() == null || getProtocols().size() == 0)

  118. && (getProvider() == null || getProvider().getProtocols() == null || getProvider().getProtocols().size() == 0)) {

  119. Map<String, ProtocolConfig> protocolConfigMap = applicationContext == null ? null : BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class, false, false);

  120. if (protocolConfigMap != null && protocolConfigMap.size() > 0) {

  121. List<ProtocolConfig> protocolConfigs = new ArrayList<ProtocolConfig>();

  122. for (ProtocolConfig config : protocolConfigMap.values()) {

  123. if (config.isDefault() == null || config.isDefault().booleanValue()) {

  124. protocolConfigs.add(config);

  125. }

  126. }

  127. //关联protocol

  128. if (protocolConfigs != null && protocolConfigs.size() > 0) {

  129. super.setProtocols(protocolConfigs);

  130. }

  131. }

  132. }

  133. //如果没有配置path

  134. if (getPath() == null || getPath().length() == 0) {

  135. if (beanName != null && beanName.length() > 0

  136. && getInterface() != null && getInterface().length() > 0

  137. && beanName.startsWith(getInterface())) {

  138. setPath(beanName);

  139. }

  140. }

  141. //暴露provider

  142. if (! isDelay()) {

  143. export();

  144. }

  145. }

      Dubbo在确认了所有相关对象都配置后调用export方法开始暴露过程:

 
  1. public synchronized void export() {

  2. //如果provider没有配置

  3. if (provider != null) {

  4. //如果exporter没有配置使用provider所关联的exporter

  5. if (export == null) {

  6. export = provider.getExport();

  7. }

  8. //如果delay(延迟暴露)没有配置,获取provider的delay

  9. if (delay == null) {

  10. delay = provider.getDelay();

  11. }

  12. }

  13. //如果不需要暴露接口则直接返回

  14. if (export != null && ! export.booleanValue()) {

  15. return;

  16. }

  17. //如果延迟暴露的时间(毫秒级)是存在的,开启线程并等待delay毫秒后开始暴露接口,否则直接执行暴露接口过程

  18. if (delay != null && delay > 0) {

  19. Thread thread = new Thread(new Runnable() {

  20. public void run() {

  21. try {

  22. Thread.sleep(delay);

  23. } catch (Throwable e) {

  24. }

  25. doExport();

  26. }

  27. });

  28. thread.setDaemon(true);

  29. thread.setName("DelayExportServiceThread");

  30. thread.start();

  31. } else {

  32. doExport();

  33. }

  34. }

 
  1. protected synchronized void doExport() {

  2. //如果不需要暴露接口则抛出异常

  3. if (unexported) {

  4. throw new IllegalStateException("Already unexported!");

  5. }

  6. //如果已经暴露则不需要重复暴露

  7. if (exported) {

  8. return;

  9. }

  10. exported = true;

  11. //如果interfaceName没配置(这样dubbo就无法找到需要暴露的service对象)则抛出异常

  12. if (interfaceName == null || interfaceName.length() == 0) {

  13. throw new IllegalStateException("<dubbo:service interface=\"\" /> interface not allow null!");

  14. }

  15. checkDefault();

  16. //provider已经配置的情况下,如果application、module、registries、monitor、protocol中有未配置的均可以从provider获取

  17. if (provider != null) {

  18. if (application == null) {

  19. application = provider.getApplication();

  20. }

  21. if (module == null) {

  22. module = provider.getModule();

  23. }

  24. if (registries == null) {

  25. registries = provider.getRegistries();

  26. }

  27. if (monitor == null) {

  28. monitor = provider.getMonitor();

  29. }

  30. if (protocols == null) {

  31. protocols = provider.getProtocols();

  32. }

  33. }

  34. if (module != null) {

  35. if (registries == null) {

  36. registries = module.getRegistries();

  37. }

  38. if (monitor == null) {

  39. monitor = module.getMonitor();

  40. }

  41. }

  42. if (application != null) {

  43. if (registries == null) {

  44. registries = application.getRegistries();

  45. }

  46. if (monitor == null) {

  47. monitor = application.getMonitor();

  48. }

  49. }

  50. if (ref instanceof GenericService) {

  51. interfaceClass = GenericService.class;

  52. if (StringUtils.isEmpty(generic)) {

  53. generic = Boolean.TRUE.toString();

  54. }

  55. } else {

  56. try {

  57. interfaceClass = Class.forName(interfaceName, true, Thread.currentThread()

  58. .getContextClassLoader());

  59. } catch (ClassNotFoundException e) {

  60. throw new IllegalStateException(e.getMessage(), e);

  61. }

  62. checkInterfaceAndMethods(interfaceClass, methods);

  63. checkRef();

  64. generic = Boolean.FALSE.toString();

  65. }

  66. //如果是本地服务

  67. if(local !=null){

  68. //如果是本地服务在interfaceName属性后面加上Local

  69. if(local=="true"){

  70. local=interfaceName+"Local";

  71. }

  72. Class<?> localClass;

  73. try {

  74. //加载service

  75. localClass = ClassHelper.forNameWithThreadContextClassLoader(local);

  76. } catch (ClassNotFoundException e) {

  77. throw new IllegalStateException(e.getMessage(), e);

  78. }

  79. if(!interfaceClass.isAssignableFrom(localClass)){

  80. throw new IllegalStateException("The local implemention class " + localClass.getName() + " not implement interface " + interfaceName);

  81. }

  82. }

  83. //如果是远程服务

  84. if(stub !=null){

  85. if(stub=="true"){

  86. stub=interfaceName+"Stub";

  87. }

  88. Class<?> stubClass;

  89. try {

  90. //加载service

  91. stubClass = ClassHelper.forNameWithThreadContextClassLoader(stub);

  92. } catch (ClassNotFoundException e) {

  93. throw new IllegalStateException(e.getMessage(), e);

  94. }

  95. if(!interfaceClass.isAssignableFrom(stubClass)){

  96. throw new IllegalStateException("The stub implemention class " + stubClass.getName() + " not implement interface " + interfaceName);

  97. }

  98. }

  99. //检查application

  100. checkApplication();

  101. //检查registries

  102. checkRegistry();

  103. //检查protocol

  104. checkProtocol();

  105. //将所有这些对象的属性关联到provider

  106. appendProperties(this);

  107. checkStubAndMock(interfaceClass);

  108. if (path == null || path.length() == 0) {

  109. path = interfaceName;

  110. }

  111. //暴露地址

  112. doExportUrls();

  113. }

 
  1. private void doExportUrls() {

  2. //将注册的所有url匹配上对应的协议在服务端暴露出来

  3. List<URL> registryURLs = loadRegistries(true);

  4. for (ProtocolConfig protocolConfig : protocols) {

  5. doExportUrlsFor1Protocol(protocolConfig, registryURLs);

  6. }

  7. }

 
  1. private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List<URL> registryURLs) {

  2. //如果没配置protocol则默认使用dubbo协议

  3. String name = protocolConfig.getName();

  4. if (name == null || name.length() == 0) {

  5. name = "dubbo";

  6. }

  7. //获取主机地址

  8. String host = protocolConfig.getHost();

  9. if (provider != null && (host == null || host.length() == 0)) {

  10. host = provider.getHost();

  11. }

  12. boolean anyhost = false;

  13. if (NetUtils.isInvalidLocalHost(host)) {

  14. anyhost = true;

  15. try {

  16. host = InetAddress.getLocalHost().getHostAddress();

  17. } catch (UnknownHostException e) {

  18. logger.warn(e.getMessage(), e);

  19. }

  20. if (NetUtils.isInvalidLocalHost(host)) {

  21. if (registryURLs != null && registryURLs.size() > 0) {

  22. for (URL registryURL : registryURLs) {

  23. try {

  24. //创建socket,连接到注册中心

  25. Socket socket = new Socket();

  26. try {

  27. SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());

  28. socket.connect(addr, 1000);

  29. //获取服务所在主机地址

  30. host = socket.getLocalAddress().getHostAddress();

  31. break;

  32. } finally {

  33. try {

  34. socket.close();

  35. } catch (Throwable e) {}

  36. }

  37. } catch (Exception e) {

  38. logger.warn(e.getMessage(), e);

  39. }

  40. }

  41. }

  42. if (NetUtils.isInvalidLocalHost(host)) {

  43. host = NetUtils.getLocalHost();

  44. }

  45. }

  46. }

  47. //获取协议接口号

  48. Integer port = protocolConfig.getPort();

  49. if (provider != null && (port == null || port == 0)) {

  50. port = provider.getPort();

  51. }

  52. final int defaultPort = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).getDefaultPort();

  53. if (port == null || port == 0) {

  54. port = defaultPort;

  55. }

  56. if (port == null || port <= 0) {

  57. port = getRandomPort(name);

  58. if (port == null || port < 0) {

  59. port = NetUtils.getAvailablePort(defaultPort);

  60. putRandomPort(name, port);

  61. }

  62. logger.warn("Use random available port(" + port + ") for protocol " + name);

  63. }

  64.  
  65. //获取application、module、provider、protocol、exporter、registries、monitor所有属性

  66. Map<String, String> map = new HashMap<String, String>();

  67. if (anyhost) {

  68. map.put(Constants.ANYHOST_KEY, "true");

  69. }

  70. map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE);

  71. map.put(Constants.DUBBO_VERSION_KEY, Version.getVersion());

  72. map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis()));

  73. if (ConfigUtils.getPid() > 0) {

  74. map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid()));

  75. }

  76. appendParameters(map, application);

  77. appendParameters(map, module);

  78. appendParameters(map, provider, Constants.DEFAULT_KEY);

  79. appendParameters(map, protocolConfig);

  80. appendParameters(map, this);

  81. if (methods != null && methods.size() > 0) {

  82. for (MethodConfig method : methods) {

  83. appendParameters(map, method, method.getName());

  84. String retryKey = method.getName() + ".retry";

  85. if (map.containsKey(retryKey)) {

  86. String retryValue = map.remove(retryKey);

  87. if ("false".equals(retryValue)) {

  88. map.put(method.getName() + ".retries", "0");

  89. }

  90. }

  91. List<ArgumentConfig> arguments = method.getArguments();

  92. if (arguments != null && arguments.size() > 0) {

  93. for (ArgumentConfig argument : arguments) {

  94. //类型自动转换.

  95. if(argument.getType() != null && argument.getType().length() >0){

  96. Method[] methods = interfaceClass.getMethods();

  97. //遍历所有方法

  98. if(methods != null && methods.length > 0){

  99. for (int i = 0; i < methods.length; i++) {

  100. String methodName = methods[i].getName();

  101. //匹配方法名称,获取方法签名.

  102. if(methodName.equals(method.getName())){

  103. Class<?>[] argtypes = methods[i].getParameterTypes();

  104. //一个方法中单个callback

  105. if (argument.getIndex() != -1 ){

  106. if (argtypes[argument.getIndex()].getName().equals(argument.getType())){

  107. appendParameters(map, argument, method.getName() + "." + argument.getIndex());

  108. }else {

  109. throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType());

  110. }

  111. } else {

  112. //一个方法中多个callback

  113. for (int j = 0 ;j<argtypes.length ;j++) {

  114. Class<?> argclazz = argtypes[j];

  115. if (argclazz.getName().equals(argument.getType())){

  116. appendParameters(map, argument, method.getName() + "." + j);

  117. if (argument.getIndex() != -1 && argument.getIndex() != j){

  118. throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType());

  119. }

  120. }

  121. }

  122. }

  123. }

  124. }

  125. }

  126. }else if(argument.getIndex() != -1){

  127. appendParameters(map, argument, method.getName() + "." + argument.getIndex());

  128. }else {

  129. throw new IllegalArgumentException("argument config must set index or type attribute.eg: <dubbo:argument index='0' .../> or <dubbo:argument type=xxx .../>");

  130. }

  131.  
  132. }

  133. }

  134. } // end of methods for

  135. }

  136.  
  137. if (ProtocolUtils.isGeneric(generic)) {

  138. map.put("generic", generic);

  139. map.put("methods", Constants.ANY_VALUE);

  140. } else {

  141. String revision = Version.getVersion(interfaceClass, version);

  142. if (revision != null && revision.length() > 0) {

  143. map.put("revision", revision);

  144. }

  145.  
  146. String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();

  147. if(methods.length == 0) {

  148. logger.warn("NO method found in service interface " + interfaceClass.getName());

  149. map.put("methods", Constants.ANY_VALUE);

  150. }

  151. else {

  152. map.put("methods", StringUtils.join(new HashSet<String>(Arrays.asList(methods)), ","));

  153. }

  154. }

  155. if (! ConfigUtils.isEmpty(token)) {

  156. if (ConfigUtils.isDefault(token)) {

  157. map.put("token", UUID.randomUUID().toString());

  158. } else {

  159. map.put("token", token);

  160. }

  161. }

  162. if ("injvm".equals(protocolConfig.getName())) {

  163. protocolConfig.setRegister(false);

  164. map.put("notify", "false");

  165. }

  166. // 导出服务

  167. String contextPath = protocolConfig.getContextpath();

  168. if ((contextPath == null || contextPath.length() == 0) && provider != null) {

  169. contextPath = provider.getContextpath();

  170. }

  171. //创建服务所在url

  172. URL url = new URL(name, host, port, (contextPath == null || contextPath.length() == 0 ? "" : contextPath + "/") + path, map);

  173.  
  174. if (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)

  175. .hasExtension(url.getProtocol())) {

  176. url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class)

  177. .getExtension(url.getProtocol()).getConfigurator(url).configure(url);

  178. }

  179.  
  180. String scope = url.getParameter(Constants.SCOPE_KEY);

  181. //配置为none不暴露

  182. if (! Constants.SCOPE_NONE.toString().equalsIgnoreCase(scope)) {

  183.  
  184. //配置不是remote的情况下做本地暴露 (配置为remote,则表示只暴露远程服务)

  185. if (!Constants.SCOPE_REMOTE.toString().equalsIgnoreCase(scope)) {

  186. //暴露的地址是localhost所以远端无法访问

  187. exportLocal(url);

  188. }

  189. //如果配置不是local则暴露为远程服务.(配置为local,则表示只暴露远程服务)

  190. if (! Constants.SCOPE_LOCAL.toString().equalsIgnoreCase(scope) ){

  191. if (logger.isInfoEnabled()) {

  192. logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url);

  193. }

  194. if (registryURLs != null && registryURLs.size() > 0

  195. && url.getParameter("register", true)) {

  196. for (URL registryURL : registryURLs) {

  197. url = url.addParameterIfAbsent("dynamic", registryURL.getParameter("dynamic"));

  198. URL monitorUrl = loadMonitor(registryURL);

  199. if (monitorUrl != null) {

  200. url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString());

  201. }

  202. if (logger.isInfoEnabled()) {

  203. logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL);

  204. }

  205. //获取invoker

  206. Invoker<?> invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString()));

  207. //根据协议将invoker暴露成exporter,具体过程是创建一个ExchangeServer,它会绑定一个ServerSocket到配置端口

  208. Exporter<?> exporter = protocol.export(invoker);

  209. //将创建的exporter放进链表便于管理

  210. exporters.add(exporter);

  211. }

  212. } else {

  213. Invoker<?> invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url);

  214.  
  215. Exporter<?> exporter = protocol.export(invoker);

  216. exporters.add(exporter);

  217. }

  218. }

  219. }

  220. this.urls.add(url);

  221. }

      整个暴露服务的流程就是首先检查配置是否完整然后获取协议和端口信息,通知registries自己已经注册可以提供服务最后创建Server绑定端口。这样用户就可以从配置的信息连接到Server并和Server通信远程调用方法了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值