一店诗、啟動(dòng)入口
這次講 dubbo-spring-boot-starter 啟動(dòng)方式,所以入口就是Spring的SPI機(jī)制;
首先在META-INF/spring.factories配置下,配置了org.apache.dubbo.spring.boot.autoconfigure.DubboAutoConfiguration類,在啟動(dòng)時(shí)丰辣,則會(huì)把DubboAutoConfiguration類注冊(cè)到spring容器中;
我們來看下DubboAutoConfiguration
先看啟動(dòng)流程
@Bean
public ServiceAnnotationBeanPostProcessor serviceAnnotationBeanPostProcessor(@Qualifier("dubboScanBasePackagesPropertyResolver") PropertyResolver propertyResolver) {
Set<String> packagesToScan = (Set)propertyResolver.getProperty("base-packages", Set.class, Collections.emptySet());
return new ServiceAnnotationBeanPostProcessor(packagesToScan);
}
我們先看下生產(chǎn)者端的啟動(dòng)流程禽捆,首先是在Spring中注冊(cè)ServiceAnnotationBeanPostProcessor類
二笙什、ServiceAnnotationBeanPostProcessor解析
我們先看下ServiceAnnotationBeanPostProcessor類該類實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor接口,則在Spring容器初始化時(shí)胚想,會(huì)調(diào)用postProcessBeanDefinitionRegistry方法
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
// 注冊(cè)DubboBootstrapApplicationListener類
registerBeans(registry, DubboBootstrapApplicationListener.class);
//獲取掃描路徑
Set<String> resolvedPackagesToScan = resolvePackagesToScan(packagesToScan);
if (!CollectionUtils.isEmpty(resolvedPackagesToScan)) {
//根據(jù)掃描路徑去掃描生成實(shí)例并注冊(cè)琐凭,且生成相應(yīng)的ServiceBean對(duì)象,且注冊(cè)到Spring中
registerServiceBeans(resolvedPackagesToScan, registry);
} else {
if (logger.isWarnEnabled()) {
logger.warn("packagesToScan is empty , ServiceBean registry will be ignored!");
}
}
}
我們會(huì)看到浊服,這個(gè)時(shí)候會(huì)去注冊(cè)DubboBootstrapApplicationListener類统屈,這個(gè)類我們等流程到了在分析,我們先按啟動(dòng)流程看過去牙躺;resolvePackagesToScan方法先獲取到需要掃描的包 愁憔,然后再調(diào)用registerServiceBeans去注冊(cè)相關(guān)實(shí)例,我們重點(diǎn)來看下registerServiceBeans方法
private void registerServiceBeans(Set<String> packagesToScan, BeanDefinitionRegistry registry) {
//new出dubbo的掃描器孽拷,主要是繼承ClassPathBeanDefinitionScanner吨掌,功能幾乎一樣,只是多了一些獲取環(huán)境參數(shù)的功能
DubboClassPathBeanDefinitionScanner scanner =
new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader);
BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry);
scanner.setBeanNameGenerator(beanNameGenerator);
//添加需要掃描的注解(主要是為了兼容以前的版本,還有會(huì)掃描alibaba這個(gè)包下的)
scanner.addIncludeFilter(new AnnotationTypeFilter(Service.class));
scanner.addIncludeFilter(new AnnotationTypeFilter(com.alibaba.dubbo.config.annotation.Service.class));
for (String packageToScan : packagesToScan) {
// 掃描到的類膜宋,就會(huì)注冊(cè)進(jìn)spring容器
scanner.scan(packageToScan);
//獲取到剛剛掃描出的類
Set<BeanDefinitionHolder> beanDefinitionHolders =
findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator);
if (!CollectionUtils.isEmpty(beanDefinitionHolders)) {
//掃描出的打有@Service注解的類窿侈,會(huì)挨個(gè)去生成ServiceBean去注冊(cè)
for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
registerServiceBean(beanDefinitionHolder, registry, scanner);
}
if (logger.isInfoEnabled()) {
logger.info(beanDefinitionHolders.size() + " annotated Dubbo's @Service Components { " +
beanDefinitionHolders +
" } were scanned under package[" + packageToScan + "]");
}
} else {
if (logger.isWarnEnabled()) {
logger.warn("No Spring Bean annotating Dubbo's @Service was found under package["
+ packageToScan + "]");
}
}
}
}
接下來,我們主要去看下registerServiceBean方法
private void registerServiceBean(BeanDefinitionHolder beanDefinitionHolder, BeanDefinitionRegistry registry,
DubboClassPathBeanDefinitionScanner scanner) {
Class<?> beanClass = resolveClass(beanDefinitionHolder);
Annotation service = findServiceAnnotation(beanClass);
//獲取當(dāng)前對(duì)象的注解參數(shù)
AnnotationAttributes serviceAnnotationAttributes = getAnnotationAttributes(service, false, false);
//獲取接口類型
Class<?> interfaceClass = resolveServiceInterfaceClass(serviceAnnotationAttributes, beanClass);
String annotatedServiceBeanName = beanDefinitionHolder.getBeanName();
//構(gòu)建serviceBean bean定義
AbstractBeanDefinition serviceBeanDefinition =
buildServiceBeanDefinition(service, serviceAnnotationAttributes, interfaceClass, annotatedServiceBeanName);
// 生成ServiceBean在Spring容器中的名稱(ServiceBean:接口全限定名+分組+版本)
String beanName = generateServiceBeanName(serviceAnnotationAttributes, interfaceClass);
//注冊(cè)ServiceBean
if (scanner.checkCandidate(beanName, serviceBeanDefinition)) { // check duplicated candidate bean
registry.registerBeanDefinition(beanName, serviceBeanDefinition);
if (logger.isInfoEnabled()) {
logger.info("The BeanDefinition[" + serviceBeanDefinition +
"] of ServiceBean has been registered with name : " + beanName);
}
} else {
if (logger.isWarnEnabled()) {
logger.warn("The Duplicated BeanDefinition[" + serviceBeanDefinition +
"] of ServiceBean[ bean name : " + beanName +
"] was be found , Did @DubboComponentScan scan to same package in many times?");
}
}
}
接下來秋茫,我們來看下buildServiceBeanDefinition方法
private AbstractBeanDefinition buildServiceBeanDefinition(Annotation serviceAnnotation,
AnnotationAttributes serviceAnnotationAttributes,
Class<?> interfaceClass,
String annotatedServiceBeanName) {
//生成ServiceBean bean定義對(duì)象
BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class);
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
//排除不需要設(shè)置的屬性
String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol",
"interface", "interfaceName", "parameters");
propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(serviceAnnotation, environment, ignoreAttributeNames));
// 設(shè)置ref對(duì)象史简,addPropertyReference則會(huì)根據(jù)名稱在Spring容器中找到相應(yīng)的對(duì)象注入進(jìn)去
addPropertyReference(builder, "ref", annotatedServiceBeanName);
// 以下都是設(shè)置ServiceBean 屬性,主要是從@Service注解參數(shù)中獲取
builder.addPropertyValue("interface", interfaceClass.getName());
// Convert parameters into map
builder.addPropertyValue("parameters", convertParameters(serviceAnnotationAttributes.getStringArray("parameters")));
// Add methods parameters
List<MethodConfig> methodConfigs = convertMethodConfigs(serviceAnnotationAttributes.get("methods"));
if (!methodConfigs.isEmpty()) {
builder.addPropertyValue("methods", methodConfigs);
}
/**
* Add {@link org.apache.dubbo.config.ProviderConfig} Bean reference
*/
String providerConfigBeanName = serviceAnnotationAttributes.getString("provider");
if (StringUtils.hasText(providerConfigBeanName)) {
addPropertyReference(builder, "provider", providerConfigBeanName);
}
/**
* Add {@link org.apache.dubbo.config.MonitorConfig} Bean reference
*/
String monitorConfigBeanName = serviceAnnotationAttributes.getString("monitor");
if (StringUtils.hasText(monitorConfigBeanName)) {
addPropertyReference(builder, "monitor", monitorConfigBeanName);
}
/**
* Add {@link org.apache.dubbo.config.ApplicationConfig} Bean reference
*/
String applicationConfigBeanName = serviceAnnotationAttributes.getString("application");
if (StringUtils.hasText(applicationConfigBeanName)) {
addPropertyReference(builder, "application", applicationConfigBeanName);
}
/**
* Add {@link org.apache.dubbo.config.ModuleConfig} Bean reference
*/
String moduleConfigBeanName = serviceAnnotationAttributes.getString("module");
if (StringUtils.hasText(moduleConfigBeanName)) {
addPropertyReference(builder, "module", moduleConfigBeanName);
}
/**
* Add {@link org.apache.dubbo.config.RegistryConfig} Bean reference
*/
String[] registryConfigBeanNames = serviceAnnotationAttributes.getStringArray("registry");
List<RuntimeBeanReference> registryRuntimeBeanReferences = toRuntimeBeanReferences(registryConfigBeanNames);
if (!registryRuntimeBeanReferences.isEmpty()) {
builder.addPropertyValue("registries", registryRuntimeBeanReferences);
}
/**
* Add {@link org.apache.dubbo.config.ProtocolConfig} Bean reference
*/
String[] protocolConfigBeanNames = serviceAnnotationAttributes.getStringArray("protocol");
List<RuntimeBeanReference> protocolRuntimeBeanReferences = toRuntimeBeanReferences(protocolConfigBeanNames);
if (!protocolRuntimeBeanReferences.isEmpty()) {
builder.addPropertyValue("protocols", protocolRuntimeBeanReferences);
}
return builder.getBeanDefinition();
}
到這肛著,ServiceBean注冊(cè)成功圆兵,ServiceBean類很重要,每個(gè)Dubbo service實(shí)例都對(duì)應(yīng)一個(gè)ServiceBean策泣,相關(guān)配置都在ServiceBean中衙傀;我們?cè)倩氐介_始注冊(cè)的DubboBootstrapApplicationListener類
三、DubboBootstrapApplicationListener解析
DubboBootstrapApplicationListener類繼承了OneTimeExecutionApplicationContextEventListener萨咕,OneTimeExecutionApplicationContextEventListener實(shí)現(xiàn)了ApplicationListener,主要監(jiān)聽了Spring容器生命周期火本,我們看下onApplicationContextEvent方法
@Override
public void onApplicationContextEvent(ApplicationContextEvent event) {
if (event instanceof ContextRefreshedEvent) {
onContextRefreshedEvent((ContextRefreshedEvent) event);
} else if (event instanceof ContextClosedEvent) {
onContextClosedEvent((ContextClosedEvent) event);
}
}
private void onContextRefreshedEvent(ContextRefreshedEvent event) {
dubboBootstrap.start();
}
我們可以看到危队,當(dāng)Spring容器啟動(dòng)成功時(shí),會(huì)調(diào)用dubboBootstrap.start()钙畔;
public DubboBootstrap start() {
if (started.compareAndSet(false, true)) {
//初始化 DubboBootstrap
initialize();
if (logger.isInfoEnabled()) {
logger.info(NAME + " is starting...");
}
// 1. 導(dǎo)出服務(wù)
exportServices();
// Not only provider register
if (!isOnlyRegisterProvider() || hasExportedServices()) {
// 導(dǎo)出服務(wù)元數(shù)據(jù)
exportMetadataService();
//注冊(cè)服務(wù)實(shí)例
registerServiceInstance();
}
//消費(fèi)端引用服務(wù)
referServices();
if (logger.isInfoEnabled()) {
logger.info(NAME + " has started.");
}
}
return this;
}
private void exportServices() {
configManager.getServices().forEach(sc -> {
ServiceConfig serviceConfig = (ServiceConfig) sc;
serviceConfig.setBootstrap(this);
if (exportAsync) {
ExecutorService executor = executorRepository.getServiceExporterExecutor();
Future<?> future = executor.submit(() -> {
//導(dǎo)出服務(wù)茫陆,調(diào)用每個(gè)注冊(cè)的ServiceBean的export方法去導(dǎo)出
sc.export();
});
asyncExportingFutures.add(future);
} else {
sc.export();
exportedServices.add(sc);
}
});
}
接下來,主要邏輯在ServiceBean中擎析,這個(gè)export方法在其父類ServiceConfig中簿盅,我們下一篇主要講ServiceConfig邏輯;