服务发布
启动流程
1.ServiceConfig#export
服务提供方在启动部署时,dubbo会调用ServiceConfig#export
来激活服务发布流程,如下所示:
- Java API:
// 1. 创建ServiceConfig实例
ServiceConfig serviceConfig = new ServiceConfig<>();
// 2. 设置应用程序配置
serviceConfig.setApplication(new ApplicationConfig(“deep-in-dubbo-first-provider”));
// 3. 设置注册中心
RegistryConfig registryConfig = new RegistryConfig(“zookeeper://127.0.0.1:2181/”);
serviceConfig.setRegistry(registryConfig);
// 4. 设置接口和实现类
// 5. 设置服务分组和版本
// dubbo中,服务接口+服务分组+服务版本 唯一的确定一个服务,同一个接口可以有不同版本,方便维护升级
serviceConfig.setInterface(IGreetingService.class);
serviceConfig.setRef(new GreetingServiceImpl());
serviceConfig.setVersion(“1.0.0”);
serviceConfig.setGroup(“dubbo-sxzhongf-group”);
RpcContext.getContext().setAttachment(“age”,“18”);
// 7. 导出服务,启动Netty监听链接请求,并将服务注册到注册中心
serviceConfig.export();
// 8. 挂起线程,避免服务停止
System.out.println("api provider service is started...");
System.in.read();
```
- XML
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://dubbo.apache.org/schema/dubbo"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
<!-- provider's application name, used for tracing dependency relationship -->
<dubbo:application name="first-xml-provider"/>
<!-- use multicast registry center to export service -->
<dubbo:registry address="zookeeper://127.0.0.1:2181/"/>
<!-- use dubbo protocol to export service on port 20880 -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- service implementation, as same as regular local bean -->
<bean id="demoService" class="com.sxzhongf.deep.in.dubbo.provider.service.impl.GreetingServiceImpl"/>
<!-- declare the service interface to be exported -->
<dubbo:service interface="com.sxzhongf.deep.in.dubbo.api.service.IGreetingService"
ref="demoService" version="1.0.0" group="dubbo-sxzhongf-group">
<dubbo:method name="sayHello" async="false" timeout="0" retries="3"></dubbo:method>
<dubbo:method name="testGeneric" async="false" timeout="10000" retries="3"></dubbo:method>
</dubbo:service>
</beans>
查看export
源码可知,总共有三种服务导出选项:
java public synchronized void export() { //1. 是否导出 if (!shouldExport()) { return; } ... //2.延迟导出 if (shouldDelay()) { DELAY_EXPORT_EXECUTOR.schedule(this::doExport, getDelay(), TimeUnit.MILLISECONDS); } else { //3.立刻导出 doExport(); } }
2.ServiceConfig#doExport
此方法主要是根据设置的属性进行合法性检查,主要包含是否已被导出,doExportUrls();
3.doExportUrls
4.ConfigValidationUtils#loadRegistries
此方法用来加载所有的服务注册中心对象,在dubbo中,一个service可以被注册到多个注册中心。
通过
doExportUrlsFor1Protocol(protocolConfig, registryURLs);
5.doExportUrlsFor1Protocol
在此方法中会将所有的参数封装成
org.apache.dubbo.common.URL
对象,然后执行具体的服务导出。
具体过程分为:
-
1.解析MethodConfig配置(单独的方法调用参数设置)
-
2.泛型调用类型设置
-
3.拼接URL参数