dubbo 使用说明
自动配置类
DubboAutoConfiguration
@ConditionalOnProperty( prefix = "dubbo", name = {"enabled"}, matchIfMissing = true ) @Configuration @AutoConfigureAfter({DubboRelaxedBindingAutoConfiguration.class}) @EnableConfigurationProperties({DubboConfigurationProperties.class}) //dubbo配置类 @EnableDubboConfig //开启dubbo配置 public class DubboAutoConfiguration { public DubboAutoConfiguration() { } @ConditionalOnProperty( prefix = "dubbo.scan.", name = {"base-packages"} ) //存在dubbo.scan.base-packages属性 @ConditionalOnBean( name = {"dubbo-service-class-base-packages"} ) //并且存在名为dubbo-service-class-base-packages的bean时, @Bean public ServiceAnnotationPostProcessor serviceAnnotationBeanProcessor(@Qualifier("dubbo-service-class-base-packages") SetpackagesToScan) { return new ServiceAnnotationPostProcessor(packagesToScan); } //创建ServiceAnnotationPostProcessor的bean }
EnableDubboConfig:是否开启dubbo配置bean多值绑定,默认开启
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @documented @import(DubboConfigConfigurationRegistrar.class) //导入DubboConfigConfigurationRegistrar类 public @interface EnableDubboConfig { boolean multiple() default true; }
DubboConfigConfigurationRegistrar:注册bean信息
public class DubboConfigConfigurationRegistrar implements importBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(Annotationmetadata importingClassmetadata, BeanDefinitionRegistry registry) { //注册bean的定义信息 // initialize dubbo beans DubboSpringInitializer.initialize(registry); //dubbo bean初始化 // Config beans creating from props have move to ConfigManager //multuiple配置bean的创建移到configManager中 // AnnotationAttributes attributes = AnnotationAttributes.fromMap( // importingClassmetadata.getAnnotationAttributes(EnableDubboConfig.class.getName())); // // boolean multiple = attributes.getBoolean("multiple"); // // // Single Config Bindings // registerBeans(registry, DubboConfigConfiguration.Single.class); // // if (multiple) { // Since 2.6.6 https://github.com/apache/dubbo/issues/3193 // registerBeans(registry, DubboConfigConfiguration.Multiple.class); // } } }
DubboSpringInitializer:dubbo初始化
public class DubboSpringInitializer { public static void initialize(BeanDefinitionRegistry registry) { //初始化 *** 作 // Spring ApplicationContext may not ready at this moment (e.g. load from xml), so use registry as key if (contextMap.putIfAbsent(registry, new DubboSpringInitContext()) != null) { return; } // prepare context and do customize DubboSpringInitContext context = contextMap.get(registry); // find beanFactory ConfigurableListableBeanFactory beanFactory = findBeanFactory(registry); // init dubbo context initContext(context, registry, beanFactory); //初始化dubbo上下文 } private static void initContext(DubboSpringInitContext context, BeanDefinitionRegistry registry, ConfigurableListableBeanFactory beanFactory) { context.setRegistry(registry); context.setBeanFactory(beanFactory); // customize context, you can change the bind module model via DubboSpringInitCustomizer SPI customize(context); // init ModuleModel ModuleModel moduleModel = context.getModuleModel(); if (moduleModel == null) { ApplicationModel applicationModel; if (findContextForApplication(ApplicationModel.defaultModel()) == null) { // first spring context use default application instance applicationModel = ApplicationModel.defaultModel(); logger.info("Use default application: " + safeGetModelDesc(applicationModel)); } else { // create an new application instance for later spring context applicationModel = frameworkModel.defaultModel().newApplication(); logger.info("Create new application: " + safeGetModelDesc(applicationModel)); } // init ModuleModel moduleModel = applicationModel.getDefaultModule(); context.setModuleModel(moduleModel); logger.info("Use default module model of target application: " + safeGetModelDesc(moduleModel)); } else { logger.info("Use module model from customizer: " + safeGetModelDesc(moduleModel)); } logger.info("Bind " + safeGetModelDesc(moduleModel) + " to spring container: " + ObjectUtils.identityToString(registry)); // set module attributes if (context.getModuleAttributes().size() > 0) { context.getModuleModel().getAttributes().putAll(context.getModuleAttributes()); } // bind dubbo initialization context to spring context registerContextBeans(beanFactory, context); // mark context as bound context.markAsBound(); // register common beans DubboBeanUtils.registerCommonBeans(registry); //注册常用bean } ... }
DubboBeanUtils:dubbo注册工具类
public interface DubboBeanUtils { static final Log log = LogFactory.getLog(DubboBeanUtils.class); static void registerCommonBeans(BeanDefinitionRegistry registry) { registerInfrastructureBean(registry, ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class); registerInfrastructureBean(registry, ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); // Since 2.5.7 Register @Reference Annotation Bean Processor as an infrastructure Bean registerInfrastructureBean(registry, ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); //注册ReferenceAnnotationBeanPostProcessor实例,处理@DubboReference注解 // TODO Whether DubboConfigAliasPostProcessor can be removed ? // Since 2.7.4 [Feature] https://github.com/apache/dubbo/issues/5093 registerInfrastructureBean(registry, DubboConfigAliasPostProcessor.BEAN_NAME, DubboConfigAliasPostProcessor.class); // Since 2.7.4 Register DubboBootstrapApplicationListener as an infrastructure Bean // registerInfrastructureBean(registry, DubboBootstrapApplicationListener.BEAN_NAME, // DubboBootstrapApplicationListener.class); // register ApplicationListeners registerInfrastructureBean(registry, DubboDeployApplicationListener.class.getName(), DubboDeployApplicationListener.class); registerInfrastructureBean(registry, DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class); // Since 2.7.6 Register DubboConfigDefaultPropertyValueBeanPostProcessor as an infrastructure Bean registerInfrastructureBean(registry, DubboConfigDefaultPropertyValueBeanPostProcessor.BEAN_NAME, DubboConfigDefaultPropertyValueBeanPostProcessor.class); // Dubbo config initializer registerInfrastructureBean(registry, DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class); // register infra bean if not exists later registerInfrastructureBean(registry, DubboInfraBeanRegisterPostProcessor.BEAN_NAME, DubboInfraBeanRegisterPostProcessor.class); } ... }
相关注解
@EnableDubbo
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @documented @EnableDubboConfig //使用注解@EnableDubboConfig @DubboComponentScan //使用注解@DubboComponentScan public @interface EnableDubbo { @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackages") String[] scanbasePackages() default {}; //等同于注解DubboComponentScan的basePackages属性 @AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses") Class>[] scanbasePackageClasses() default {}; //等同于注解DubboComponentScan的basePackageClasses属性 @AliasFor(annotation = EnableDubboConfig.class, attribute = "multiple") boolean multipleConfig() default true; //等同于注解EnableDubboConfig的multiple的属性 }
DubboComponentScan:扫描指定包或者类,如果类上有注解@DubboService,创建bean
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @documented @import(DubboComponentScanRegistrar.class) //引入DubboComponentScanRegistrar类 public @interface DubboComponentScan { String[] value() default {}; String[] basePackages() default {}; Class>[] basePackageClasses() default {}; }
DubboComponentScanRegistrar
public class DubboComponentScanRegistrar implements importBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(Annotationmetadata importingClassmetadata, BeanDefinitionRegistry registry) { //注册类定义信息 // initialize dubbo beans DubboSpringInitializer.initialize(registry); SetpackagesToScan = getPackagesToScan(importingClassmetadata); registerServiceAnnotationPostProcessor(packagesToScan, registry); //注册ServiceAnnotationPostProcessor处理器,处理@DubboService注解 } private void registerServiceAnnotationPostProcessor(Set packagesToScan, BeanDefinitionRegistry registry) { //注册ServiceAnnotationPostProcessor处理器 BeanDefinitionBuilder builder = rootBeanDefinition(ServiceAnnotationPostProcessor.class); builder.addConstructorArgValue(packagesToScan); builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry); } private Set getPackagesToScan(Annotationmetadata metadata) { // get from @DubboComponentScan Set packagesToScan = getPackagesToScan0(metadata, DubboComponentScan.class, "basePackages", "basePackageClasses"); // get from @EnableDubbo, compatible with spring 3.x if (packagesToScan.isEmpty()) { packagesToScan = getPackagesToScan0(metadata, EnableDubbo.class, "scanbasePackages", "scanbasePackageClasses"); } if (packagesToScan.isEmpty()) { return Collections.singleton(ClassUtils.getPackageName(metadata.getClassName())); } return packagesToScan; } private Set getPackagesToScan0(Annotationmetadata metadata, Class annotationClass, String basePackagesName, String basePackageClassesName) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( metadata.getAnnotationAttributes(annotationClass.getName())); if (attributes == null) { return Collections.emptySet(); } Set packagesToScan = new linkedHashSet<>(); // basePackages String[] basePackages = attributes.getStringArray(basePackagesName); packagesToScan.addAll(Arrays.asList(basePackages)); // basePackageClasses Class>[] basePackageClasses = attributes.getClassArray(basePackageClassesName); for (Class> basePackageClass : basePackageClasses) { packagesToScan.add(ClassUtils.getPackageName(basePackageClass)); } // value if (attributes.containsKey("value")) { String[] value = attributes.getStringArray("value"); packagesToScan.addAll(Arrays.asList(value)); } return packagesToScan; } }
配置类
DubboConfiguratinProperties
@ConfigurationProperties("dubbo") public class DubboConfigurationProperties { @NestedConfigurationProperty private DubboConfigurationProperties.Config config = new DubboConfigurationProperties.Config(); @NestedConfigurationProperty private DubboConfigurationProperties.Scan scan = new DubboConfigurationProperties.Scan(); @NestedConfigurationProperty private ApplicationConfig application = new ApplicationConfig(); @NestedConfigurationProperty private ModuleConfig module = new ModuleConfig(); @NestedConfigurationProperty private RegistryConfig registry = new RegistryConfig(); @NestedConfigurationProperty private ProtocolConfig protocol = new ProtocolConfig(); @NestedConfigurationProperty private MonitorConfig monitor = new MonitorConfig(); @NestedConfigurationProperty private ProviderConfig provider = new ProviderConfig(); @NestedConfigurationProperty private ConsumerConfig consumer = new ConsumerConfig(); @NestedConfigurationProperty private ConfigCenterBean configCenter = new ConfigCenterBean(); @NestedConfigurationProperty private metadataReportConfig metadataReport = new metadataReportConfig(); @NestedConfigurationProperty private MetricsConfig metrics = new MetricsConfig(); private Mapmodules = new linkedHashMap(); private Map registries = new linkedHashMap(); private Map protocols = new linkedHashMap(); private Map monitors = new linkedHashMap(); private Map providers = new linkedHashMap(); private Map consumers = new linkedHashMap(); private Map configCenters = new linkedHashMap(); private Map metadataReports = new linkedHashMap(); private Map metricses = new linkedHashMap(); public DubboConfigurationProperties() { } ****** 内部类:Scan static class Scan { private Set basePackages = new linkedHashSet(); Scan() { } public Set getbasePackages() { return this.basePackages; } public void setbasePackages(Set basePackages) { this.basePackages = basePackages; } } ****** 内部类:Config static class Config { private ConfigMode mode; private boolean multiple; private boolean override; Config() { this.mode = ConfigMode.STRICT; this.multiple = true; this.override = true; }
AbstractConfig
public abstract class AbstractConfig implements Serializable { protected static final Logger logger = LoggerFactory.getLogger(AbstractConfig.class); private static final long serialVersionUID = 4267533505537413570L; private static final MaptagNameCache = new ConcurrentHashMap<>(); private static final Map > attributedMethodCache = new ConcurrentHashMap<>(); private static final String[] SUFFIXES = new String[]{"Config", "Bean", "Configbase"}; private String id; protected final AtomicBoolean refreshed = new AtomicBoolean(false); protected Boolean isDefault; protected ScopeModel scopeModel; public AbstractConfig() { this(ApplicationModel.defaultModel()); } public AbstractConfig(ScopeModel scopeModel) { this.setScopeModel(scopeModel); }
ScopeModel
public abstract class ScopeModel implements ExtensionAccessor { protected static final Logger LOGGER = LoggerFactory.getLogger(ScopeModel.class); private String internalId; private String modelName; private String desc; private SetclassLoaders; private final ScopeModel parent; private final ExtensionScope scope; private ExtensionDirector extensionDirector; private ScopeBeanFactory beanFactory; private List destroyListeners; private Map attributes; private final AtomicBoolean destroyed = new AtomicBoolean(false); public ScopeModel(ScopeModel parent, ExtensionScope scope) { this.parent = parent; this.scope = scope; }
ApplicationConfig
public class ApplicationConfig extends AbstractConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationConfig.class); private static final long serialVersionUID = 5508512956753757169L; private String name; private String version; private String owner; private String organization; private String architecture; private String environment; private String compiler; private String logger; private Listregistries; private String registryIds; private MonitorConfig monitor; private String dumpDirectory; private Boolean qosEnable; private String qosHost; private Integer qosPort; private Boolean qosAcceptForeignIp; private Map parameters; private String shutwait; private String hostname; private String metadataType; private Boolean registerConsumer; private String repository; private Boolean enableFileCache; private String protocol; private String metadataServiceProtocol; private Integer metadataServicePort; private String livenessProbe; private String readinessProbe; private String startupProbe; private String registerMode; //provider注册类型,可选值:all(默认)、interface(接口粒度)、instance(应用粒度) private Boolean enableEmptyProtection; public ApplicationConfig() { public ApplicationConfig(ApplicationModel applicationModel) { public ApplicationConfig(String name) { public ApplicationConfig(ApplicationModel applicationModel, String name) {
ModuleConfig
public class ModuleConfig extends AbstractConfig { private static final long serialVersionUID = 5508512956753757169L; private String name; private String version; private String owner; private String organization; private Listregistries; //注册中心配置 private MonitorConfig monitor; //监控中心配置 private Boolean background; private Boolean referAsync; //是否异步引用 private Integer referThreadNum; //消费端引用线程池大小 private Boolean exportAsync; //provider是否异步暴露 private Integer exportThreadNum; //provider暴露线程池大小 public ModuleConfig() { public ModuleConfig(ModuleModel moduleModel) { public ModuleConfig(String name) { public ModuleConfig(ModuleModel moduleModel, String name) {
RegistryConfig:注册中心配置
public class RegistryConfig extends AbstractConfig { public static final String NO_AVAILABLE = "N/A"; private static final long serialVersionUID = 5508512956753757169L; private String address; //注册中心地址 private String username; //用户名 private String password; //密码 private Integer port; //注册中心端口 private String protocol; private String transporter; private String server; private String client; private String cluster; private String zone; private String group; private String version; private Integer timeout; private Integer session; private String file; private Integer wait; private Boolean check; private Boolean dynamic; private Boolean register; //是否向注册中心暴露服务 private Boolean subscribe; private Mapparameters; private Boolean simplified; private String extraKeys; private Boolean useAsConfigCenter; private Boolean useAsmetadataCenter; private String accepts; private Boolean preferred; private Integer weight; private String registerMode; //注册模式,可选值:all(默认)、interface(接口粒度)、instance(应用粒度) private Boolean enableEmptyProtection; public RegistryConfig() { public RegistryConfig(ApplicationModel applicationModel) { public RegistryConfig(String address) { public RegistryConfig(ApplicationModel applicationModel, String address) { public RegistryConfig(String address, String protocol) { public RegistryConfig(ApplicationModel applicationModel, String address, String protocol) {
MonitorConfig:监控中心配置
public class MonitorConfig extends AbstractConfig { private static final long serialVersionUID = -1184681514659198203L; private String protocol; private String address; private String username; private String password; private String group; private String version; private String interval; private Mapparameters; //自定义的参数 public MonitorConfig() { public MonitorConfig(ApplicationModel applicationModel) { public MonitorConfig(String address) { public MonitorConfig(ApplicationModel applicationModel, String address) {
ProviderConfig:provider配置
public class ProviderConfig extends AbstractServiceConfig { private static final long serialVersionUID = 6913423882496634749L; // ======== protocol default values, it'll take effect when protocol's attributes are not set ======== private String host; private Integer port; private String contextpath; private String threadpool; private String threadname; private Integer threads; private Integer iothreads; private Integer alive; private Integer queues; private Integer accepts; private String codec; private String charset; private Integer payload; private Integer buffer; private String transporter; private String exchanger; private String dispatcher; private String networker; private String server; private String client; private String telnet; private String prompt; private String status; private Integer wait; private Integer exportThreadNum; private Boolean exportBackground; public ProviderConfig() { public ProviderConfig(ModuleModel moduleModel) {
ConsumerConfig:consumer配置
public class ConsumerConfig extends AbstractReferenceConfig { private static final long serialVersionUID = 2827274711143680600L; private String client; private String threadpool; private Integer corethreads; private Integer threads; private Integer queues; private Integer shareconnections; private String urlMergeProcessor; private Integer referThreadNum; private Boolean referBackground; public ConsumerConfig() { public ConsumerConfig(ModuleModel moduleModel) {
ConfigCenterBean:配置中心实例
public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationContextAware, DisposableBean, EnvironmentAware { private transient ApplicationContext applicationContext; private Boolean includeSpringEnv = false; public ConfigCenterBean() { }
ConfigCneterConfig:配置中心配置
public class ConfigCenterConfig extends AbstractConfig { private final AtomicBoolean initialized = new AtomicBoolean(false); private String protocol; private String address; private Integer port; private String cluster; private String namespace; private String group; private String username; private String password; private Long timeout; private Boolean highestPriority; private Boolean check; private String configFile; private String appConfigFile; private Mapparameters; //自定义参数 private Map externalConfiguration; private Map appExternalConfiguration; public ConfigCenterConfig() { public ConfigCenterConfig(ApplicationModel applicationModel) {
metadataReportConfig:元数据中心配置
public class metadataReportConfig extends AbstractConfig { private static final long serialVersionUID = 55233L; private String protocol; private String address; //元数据中心地址 private Integer port; //元数据中心端口 private String username; //元数据中心用户名 private String password; //元数据中心密码 private Integer timeout; //请求超时时间,单位毫秒 private String group; private Mapparameters; //自定义参数 private Integer retryTimes; //重试次数 private Integer retryPeriod; //重试周期 private Boolean cycleReport; //是否每天存储全部元数据 private Boolean syncReport; //是否同步存储,默认异步 private Boolean cluster; private String registry; private String file; private Boolean check; public metadataReportConfig() { public metadataReportConfig(ApplicationModel applicationModel) { public metadataReportConfig(String address) { public metadataReportConfig(ApplicationModel applicationModel, String address) {
MetricsConfig:指标运维配置
public class MetricsConfig extends AbstractConfig { private static final long serialVersionUID = -9089919311611546383L; private String protocol; @Deprecated private String port; @Nested private PrometheusConfig prometheus; //prometheus配置 @Nested private AggregationConfig aggregation; //聚合配置 public MetricsConfig() { public MetricsConfig(ApplicationModel applicationModel) {
PrometheusConfig:prometheus配置
public class PrometheusConfig { @Nested private Exporter exporter; @Nested private Pushgateway pushgateway; ******* 内部类:Exporter public static class Exporter { private Boolean enabled; private Boolean enableHttpServiceDiscovery; private String httpServiceDiscoveryUrl; private Integer metricsPort; private String metricsPath; ******* 内部类:Pushgateway public static class Pushgateway { private Boolean enabled; private String baseUrl; private String username; private String password; private Integer pushInterval; private String job;
AggregationConfig:聚合配置
public class AggregationConfig { private Boolean enabled; private Integer bucketNum; private Integer timeWindowSeconds;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)