Commit 53b2c69a by 刘宇峰

框架完善-兼容zk版本

1 parent 13dcf27f
...@@ -13,59 +13,49 @@ ...@@ -13,59 +13,49 @@
<properties> <properties>
<curator.version>4.2.0</curator.version> <curator.version>4.2.0</curator.version>
<dubbo.version>2.7.7</dubbo.version>
<zookeeper.version>3.4.6</zookeeper.version> <zookeeper.version>3.4.6</zookeeper.version>
</properties> </properties>
<dependencyManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.dubbo</groupId> <groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-bom</artifactId> <artifactId>dubbo-spring-boot-starter</artifactId>
<version>3.0.2.1</version> <version>${dubbo.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-discovery</artifactId>
<version>${curator.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>${dubbo.version}</version>
<type>pom</type>
<!-- 4.0.0原生不兼容zk 3.4, 必须进行兼容性处理 -->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId> <groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId> <artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version> </exclusion>
</dependency> <exclusion>
</dependencies> <groupId>org.slf4j</groupId>
</dependencyManagement> <artifactId>slf4j-log4j12</artifactId>
</exclusion>
<dependencies> </exclusions>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>com.101tec</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> <artifactId>zkclient</artifactId>
<version>0.11</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-discovery</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.zookeeper</groupId> <groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId> <artifactId>zookeeper</artifactId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-discovery</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId> <groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId> <artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version> <version>${zookeeper.version}</version>
<!--排除这个slf4j-log4j12-->
<exclusions> <exclusions>
<exclusion> <exclusion>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
......
package com.glsx.plat.dubbo.config;
import com.alibaba.spring.context.config.ConfigurationBeanBinder;
import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver;
import org.springframework.boot.context.properties.bind.handler.IgnoreErrorsBindHandler;
import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.UnboundElementsSourceFilter;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import java.util.Map;
import static java.util.Arrays.asList;
import static org.springframework.boot.context.properties.source.ConfigurationPropertySources.from;
/**
* Spring Boot Relaxed {@link DubboConfigBinder} implementation
* see org.springframework.boot.context.properties.ConfigurationPropertiesBinder
*
* @since 2.7.0
*/
class BinderDubboConfigBinder implements ConfigurationBeanBinder {
@Override
public void bind(Map<String, Object> configurationProperties, boolean ignoreUnknownFields,
boolean ignoreInvalidFields, Object configurationBean) {
Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties));
// Converts ConfigurationPropertySources
Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources);
// Wrap Bindable from DubboConfig instance
Bindable bindable = Bindable.ofInstance(configurationBean);
Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources));
// Get BindHandler
BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields);
// Bind
binder.bind("", bindable, bindHandler);
}
private BindHandler getBindHandler(boolean ignoreUnknownFields,
boolean ignoreInvalidFields) {
BindHandler handler = BindHandler.DEFAULT;
if (ignoreInvalidFields) {
handler = new IgnoreErrorsBindHandler(handler);
}
if (!ignoreUnknownFields) {
UnboundElementsSourceFilter filter = new UnboundElementsSourceFilter();
handler = new NoUnboundElementsBindHandler(handler, filter);
}
return handler;
}
}
package com.glsx.plat.dubbo.config;
import org.apache.dubbo.common.utils.Assert;
import org.springframework.core.env.PropertyResolver;
import org.springframework.lang.Nullable;
/**
* Delegating {@link PropertyResolver}
*
* @since 2.7.1
*/
class DelegatingPropertyResolver implements PropertyResolver {
private final PropertyResolver delegate;
DelegatingPropertyResolver(PropertyResolver delegate) {
Assert.notNull(delegate, "The delegate of PropertyResolver must not be null");
this.delegate = delegate;
}
@Override
public boolean containsProperty(String key) {
return delegate.containsProperty(key);
}
@Override
@Nullable
public String getProperty(String key) {
return delegate.getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return delegate.getProperty(key, defaultValue);
}
@Override
@Nullable
public <T> T getProperty(String key, Class<T> targetType) {
return delegate.getProperty(key, targetType);
}
@Override
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
return delegate.getProperty(key, targetType, defaultValue);
}
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
return delegate.getRequiredProperty(key);
}
@Override
public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
return delegate.getRequiredProperty(key, targetType);
}
@Override
public String resolvePlaceholders(String text) {
return delegate.resolvePlaceholders(text);
}
@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
return delegate.resolveRequiredPlaceholders(text);
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.plat.dubbo.config;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.glsx.plat.dubbo.factory.ReferenceBuilderFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceClassPostProcessor;
import org.apache.dubbo.spring.boot.autoconfigure.DubboRelaxedBinding2AutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import java.util.HashSet;
import java.util.Set;
import static org.apache.dubbo.spring.boot.util.DubboUtils.DUBBO_PREFIX;
import static org.apache.dubbo.spring.boot.util.DubboUtils.PROPERTY_NAME_SEPARATOR;
/**
* Dubbo Auto {@link Configuration}
*
* @see DubboReference
* @see DubboService
* @see ServiceClassPostProcessor
* @see ReferenceAnnotationBeanPostProcessor
* @since 2.7.0
*/
//@Configuration
//@AutoConfigureAfter(DubboRelaxedBinding2AutoConfiguration.class)
//@EnableConfigurationProperties(DubboConfigurationProperties.class)
//@Import({DubboRelaxedBinding2AutoConfiguration.class})
public class DubboAutoConfiguration {
/**
* service类,服务提供者的BeanDefinitionRegistryPostProcessor类,用来解析 * @Service, @DubboService注解,生成Service的BeanDefinition类,放入spring容器,供spring容器生成Bean
* modify by alvin.zengqi
*
* @param propertyResolver
* @param properties
* @return
* @since 2.6.0
*/
@Bean
public ServiceClassPostProcessor serviceClassPostProcessor(PropertyResolver propertyResolver, DubboConfigurationProperties properties) {
Set<String> packagesToScan = new HashSet<>();
if (properties.getScan() != null && properties.getScan().getBasePackages() != null) {
packagesToScan = properties.getScan().getBasePackages();
}
// 兼容alibaba dubbo低版本scan
String scanPackage = propertyResolver.getProperty("dubbo.scan", String.class);
packagesToScan.add(scanPackage);
return new ServiceClassPostProcessor(packagesToScan);
}
/**
* 用来解析@Reference,@DubboReference 注解,消费者引用哪些服务,通过这个注解来进行引用 * 给标注这个@Reference,@DubboReference注解的属性赋值, 和@autowired的做法类似
* Creates {@link ReferenceAnnotationBeanPostProcessor} Bean if Absent
*
* @return {@link ReferenceAnnotationBeanPostProcessor}
*/
@ConditionalOnMissingBean
@Bean(name = ReferenceAnnotationBeanPostProcessor.BEAN_NAME)
public ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor() {
return new ReferenceAnnotationBeanPostProcessor();
}
/**
* Build a primary {@link PropertyResolver} bean to {@link Autowired @Autowired}
*
* @param environment {@link Environment}
* @return alias bean for {@link Environment}
* @since 2.7.3
*/
@Bean
@Primary
public PropertyResolver primaryPropertyResolver(Environment environment) {
return environment;
}
public static final String DUBBO_LOG_TRACING_SUFFIX = "log.trace";
public static final String DUBBO_LOG_TRACING_PROPERTY = DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR + DUBBO_LOG_TRACING_SUFFIX;
/**
* 注册Reference构建工厂类
*
* @param env
* @return
*/
@Bean
public ReferenceBuilderFactory referenceBuilderFactory(ApplicationConfig config, PropertyResolver env) {
ReferenceBuilderFactory reference = new ReferenceBuilderFactory();
Boolean traceEnable = env.getProperty(DUBBO_LOG_TRACING_PROPERTY, Boolean.class);
if (null != traceEnable && !traceEnable) {
reference.setDefaultFilter("-logTrace");
}
return reference;
}
@Bean
@ConditionalOnProperty(prefix = DUBBO_PREFIX, name = DUBBO_LOG_TRACING_SUFFIX, havingValue = "false")
public ProviderConfig providerConfig(ApplicationConfig application, RegistryConfig registryConfig) {
ProviderConfig providerConfig = new ProviderConfig();
providerConfig.setFilter("-logTrace");
providerConfig.setRegistry(registryConfig);
return providerConfig;
}
}
package com.glsx.plat.dubbo.config;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.dubbo.config.*;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.spring.boot.util.DubboUtils.*;
/**
* Dubbo {@link ConfigurationProperties Config Properties} only used to generate JSON metadata(non-public class)
*
* @since 2.7.1
*/
//@ConfigurationProperties(DUBBO_PREFIX)
class DubboConfigurationProperties {
@NestedConfigurationProperty
private Config config = new Config();
@NestedConfigurationProperty
private Scan scan = new Scan();
// Single Config Bindings
@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();
// Multiple Config Bindings
private Map<String, ModuleConfig> modules = new LinkedHashMap<>();
private Map<String, RegistryConfig> registries = new LinkedHashMap<>();
private Map<String, ProtocolConfig> protocols = new LinkedHashMap<>();
private Map<String, MonitorConfig> monitors = new LinkedHashMap<>();
private Map<String, ProviderConfig> providers = new LinkedHashMap<>();
private Map<String, ConsumerConfig> consumers = new LinkedHashMap<>();
private Map<String, ConfigCenterBean> configCenters = new LinkedHashMap<>();
private Map<String, MetadataReportConfig> metadataReports = new LinkedHashMap<>();
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
public Scan getScan() {
return scan;
}
public void setScan(Scan scan) {
this.scan = scan;
}
public ApplicationConfig getApplication() {
return application;
}
public void setApplication(ApplicationConfig application) {
this.application = application;
}
public ModuleConfig getModule() {
return module;
}
public void setModule(ModuleConfig module) {
this.module = module;
}
public RegistryConfig getRegistry() {
return registry;
}
public void setRegistry(RegistryConfig registry) {
this.registry = registry;
}
public ProtocolConfig getProtocol() {
return protocol;
}
public void setProtocol(ProtocolConfig protocol) {
this.protocol = protocol;
}
public MonitorConfig getMonitor() {
return monitor;
}
public void setMonitor(MonitorConfig monitor) {
this.monitor = monitor;
}
public ProviderConfig getProvider() {
return provider;
}
public void setProvider(ProviderConfig provider) {
this.provider = provider;
}
public ConsumerConfig getConsumer() {
return consumer;
}
public void setConsumer(ConsumerConfig consumer) {
this.consumer = consumer;
}
public ConfigCenterBean getConfigCenter() {
return configCenter;
}
public void setConfigCenter(ConfigCenterBean configCenter) {
this.configCenter = configCenter;
}
public MetadataReportConfig getMetadataReport() {
return metadataReport;
}
public void setMetadataReport(MetadataReportConfig metadataReport) {
this.metadataReport = metadataReport;
}
public Map<String, ModuleConfig> getModules() {
return modules;
}
public void setModules(Map<String, ModuleConfig> modules) {
this.modules = modules;
}
public Map<String, RegistryConfig> getRegistries() {
return registries;
}
public void setRegistries(Map<String, RegistryConfig> registries) {
this.registries = registries;
}
public Map<String, ProtocolConfig> getProtocols() {
return protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
}
public Map<String, MonitorConfig> getMonitors() {
return monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return consumers;
}
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
public Map<String, ConfigCenterBean> getConfigCenters() {
return configCenters;
}
public void setConfigCenters(Map<String, ConfigCenterBean> configCenters) {
this.configCenters = configCenters;
}
public Map<String, MetadataReportConfig> getMetadataReports() {
return metadataReports;
}
public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) {
this.metadataReports = metadataReports;
}
static class Config {
/**
* Indicates multiple properties binding from externalized configuration or not.
*/
private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE;
/**
* The property name of override Dubbo config
*/
private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE;
public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
static class Scan {
/**
* The basePackages to scan , the multiple-value is delimited by comma
*
* @see EnableDubbo#scanBasePackages()
*/
private Set<String> basePackages = new LinkedHashSet<>();
public Set<String> getBasePackages() {
return basePackages;
}
public void setBasePackages(Set<String> basePackages) {
this.basePackages = basePackages;
}
}
}
package com.glsx.plat.dubbo.config;
import static com.alibaba.spring.util.PropertySourcesUtils.getSubProperties;
import static org.apache.dubbo.spring.boot.util.DubboUtils.*;
import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;
import java.util.Map;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertyResolver;
import com.alibaba.spring.context.config.ConfigurationBeanBinder;
/**
* Dubbo Relaxed Binding Auto-{@link Configuration} for Spring Boot 2.0
*
* @see DubboRelaxedBindingAutoConfiguration
* @since 2.7.0
*/
//@Configuration
//@ConditionalOnClass(name = "org.springframework.boot.context.properties.bind.Binder")
public class DubboRelaxedBinding2AutoConfiguration {
@Bean(name = BASE_PACKAGES_PROPERTY_RESOLVER_BEAN_NAME)
public PropertyResolver dubboScanBasePackagesPropertyResolver(ConfigurableEnvironment environment) {
ConfigurableEnvironment propertyResolver = new AbstractEnvironment() {
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
Map<String, Object> dubboScanProperties = getSubProperties(environment.getPropertySources(), DUBBO_SCAN_PREFIX);
propertySources.addLast(new MapPropertySource("dubboScanProperties", dubboScanProperties));
}
};
return new DelegatingPropertyResolver(propertyResolver);
}
@ConditionalOnMissingBean(name = RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME, value = ConfigurationBeanBinder.class)
@Bean(RELAXED_DUBBO_CONFIG_BINDER_BEAN_NAME)
@Scope(scopeName = SCOPE_PROTOTYPE)
public ConfigurationBeanBinder relaxedDubboConfigBinder() {
return new BinderDubboConfigBinder();
}
}
package com.glsx.plat.dubbo.env;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static org.apache.dubbo.spring.boot.util.DubboUtils.*;
/**
* The lowest precedence {@link EnvironmentPostProcessor} processes
* {@link SpringApplication#setDefaultProperties(Properties) Spring Boot default properties} for Dubbo
* as late as possible before {@link ConfigurableApplicationContext#refresh() application context refresh}.
*/
public class DubboDefaultPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
/**
* The name of default {@link PropertySource} defined in SpringApplication#configurePropertySources method.
*/
public static final String PROPERTY_SOURCE_NAME = "defaultProperties";
/**
* The property name of "spring.main.allow-bean-definition-overriding".
* Please refer to: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes#bean-overriding
*/
public static final String ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY = "spring.main.allow-bean-definition-overriding";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
MutablePropertySources propertySources = environment.getPropertySources();
Map<String, Object> defaultProperties = createDefaultProperties(environment);
if (!CollectionUtils.isEmpty(defaultProperties)) {
addOrReplace(propertySources, defaultProperties);
}
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
private Map<String, Object> createDefaultProperties(ConfigurableEnvironment environment) {
Map<String, Object> defaultProperties = new HashMap<>();
setDubboApplicationNameProperty(environment, defaultProperties);
setDubboConfigMultipleProperty(defaultProperties);
setDubboApplicationQosEnableProperty(defaultProperties);
setAllowBeanDefinitionOverriding(defaultProperties);
return defaultProperties;
}
private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) {
String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY);
if (StringUtils.hasLength(springApplicationName)
&& !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) {
defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName);
}
}
private void setDubboConfigMultipleProperty(Map<String, Object> defaultProperties) {
defaultProperties.put(DUBBO_CONFIG_MULTIPLE_PROPERTY, Boolean.TRUE.toString());
}
private void setDubboApplicationQosEnableProperty(Map<String, Object> defaultProperties) {
defaultProperties.put(DUBBO_APPLICATION_QOS_ENABLE_PROPERTY, Boolean.FALSE.toString());
}
/**
* Set {@link #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY "spring.main.allow-bean-definition-overriding"} to be
* <code>true</code> as default.
*
* @param defaultProperties the default {@link Properties properties}
* @see #ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY
* @since 2.7.1
*/
private void setAllowBeanDefinitionOverriding(Map<String, Object> defaultProperties) {
defaultProperties.put(ALLOW_BEAN_DEFINITION_OVERRIDING_PROPERTY, Boolean.TRUE.toString());
}
/**
* Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)
*
* @param propertySources {@link MutablePropertySources}
* @param map Default Dubbo Properties
*/
private void addOrReplace(MutablePropertySources propertySources,
Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) {
target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
}
package com.glsx.plat.dubbo.env;
import org.apache.dubbo.spring.boot.util.DubboUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.CollectionUtils;
import java.util.Map;
import java.util.SortedMap;
/**
* @author Alvin
* @version V1.0
* @Title: OreDubboPropertiesEnvironmentPostProcessor.java
* @Description: ore dubbo 配置处理
* @date 2020年8月28日 上午10:42:57
* @Company: didihu.com.cn
* @Copyright Copyright (c) 2020
*/
public class DubboPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
/**
* Gets Logger After LoggingSystem configuration ready
*
* @see LoggingApplicationListener
*/
Logger logger = LoggerFactory.getLogger(getClass());
public static final String PROPERTY_SOURCE_NAME = "oreDubboProperties";
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,
SpringApplication application) {
MutablePropertySources propertySources = environment.getPropertySources();
SortedMap<String, Object> dubboProperties = DubboUtils.filterDubboProperties(environment);
if (!CollectionUtils.isEmpty(dubboProperties)) {
addOrReplace(propertySources, dubboProperties);
}
if (logger.isInfoEnabled()) {
logger.info("Dubbo Config was overridden by ore externalized configuration {}", dubboProperties);
}
}
/**
* Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)
*
* @param propertySources {@link MutablePropertySources}
* @param map ore Dubbo Properties
*/
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) {
target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
}
package com.glsx.plat.dubbo.factory;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.util.List;
public interface ReferenceBuilder<T> {
/**
* 可选参数,服务方法调用超时时间(毫秒)
* 缺省使用dubbo:consumer的timeout
*
* @param timeout
* @return this
*/
ReferenceBuilder<T> timeout(Integer timeout);
/**
* 可选参数,服务版本,与服务提供者的版本一致
*
* @param version
* @return this
*/
ReferenceBuilder<T> version(String version);
/**
* 可选参数,启动时检查提供者是否存在,true报错,false忽略
* 缺省使用dubbo:consumer的check
*
* @param check
* @return
*/
ReferenceBuilder<T> check(Boolean check);
/**
* 可选参数,点对点直连服务提供者地址,将绕过注册中心
*
* @param url
* @return
*/
ReferenceBuilder<T> url(String url);
/**
* 可选参数,服务分组,当一个接口有多个实现,可以用分组区分,必需和服务提供方一致
*
* @param group
* @return
*/
ReferenceBuilder<T> group(String group);
/**
* 可选参数,远程服务调用重试次数,不包括第一次调用,不需要重试请设为0
* 缺省使用dubbo:consumer的retries
*
* @param retries
* @return
*/
ReferenceBuilder<T> retries(Integer retries);
/**
* 可选参数,只调用指定协议的服务提供方,其它协议忽略。
*
* @param protocol
* @return
*/
ReferenceBuilder<T> protocol(String protocol);
/**
* 可选参数,对每个提供者的最大连接数,rmi、http、hessian等短连接协议表示限制连接数,dubbo等长连接协表示建立的长连接个数
* 缺省使用dubbo:consumer的connections
*
* @param connections
* @return
*/
ReferenceBuilder<T> connections(Integer connections);
/**
* 可选参数,负载均衡策略,可选值:random,roundrobin,leastactive,分别表示:随机,轮循,最少活跃调用
* 缺省使用dubbo:consumer的loadbalance
*
* @param loadbalance
* @return
*/
ReferenceBuilder<T> loadbalance(String loadbalance);
/**
* 可选参数,是否异步执行,不可靠异步,只是忽略返回值,不阻塞执行线程
* 缺省使用dubbo:consumer的async
*
* @param async
* @return
*/
ReferenceBuilder<T> async(Boolean async);
/**
* 可选参数,选择动态代理实现策略,可选:javassist, jdk。
* 缺省为:javassist
*
* @param proxy
* @return
*/
ReferenceBuilder<T> proxy(String proxy);
/**
* 可选参数,每服务消费者每服务每方法最大并发调用数。
* 缺省为:0
*
* @param actives
* @return
*/
ReferenceBuilder<T> actives(Integer actives);
/**
* 可选参数,客户端传输类型设置,如Dubbo协议的netty或mina。
*
* @param client
* @return
*/
ReferenceBuilder<T> client(String client);
/**
* 可选参数,方法级参数配置,如设置单个方法的超时时间、重试次数等
*
* @param method
* @return
* @Description:
* @author Alvin.zengqi
* @date 2018年1月27日 下午3:21:35
*/
ReferenceBuilder<T> method(MethodConfig method);
/**
* 可选参数,方法级参数配置,如设置多个方法的超时时间、重试次数等
*
* @param methods
* @return
* @Description:
* @author Alvin.zengqi
* @date 2018年1月27日 下午3:21:35
*/
ReferenceBuilder<T> methods(List<MethodConfig> methods);
/**
* 增加过滤器配置
*
* @param filterName
* @return
*/
ReferenceBuilder<T> filter(String filterName);
/**
* 增加注册中心配置
*
* @param registry
* @return
*/
ReferenceBuilder<T> registry(RegistryConfig registry);
/**
* 增加路由标签配置
*
* @param tagName
* @return
*/
ReferenceBuilder<T> tag(String tagName);
// 构造
T build();
}
package com.glsx.plat.dubbo.factory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import java.util.ArrayList;
import java.util.List;
public class ReferenceBuilderFactory {
@Autowired
private ApplicationConfig config;
@Autowired
private RegistryConfig registry;
@Autowired
private Environment env;
private String defaultFilter;
public <T> ReferenceBuilder<T> builder(Class<T> clazz) {
return new DefaultBuilder<T>(clazz);
}
private class DefaultBuilder<T> implements ReferenceBuilder<T> {
private ReferenceConfig<T> reference = new ReferenceConfig<T>();
DefaultBuilder(Class<T> clazz) {
config.setRegistry(registry);
reference.setInterface(clazz);
if (StringUtils.isNotEmpty(defaultFilter)) {
reference.setFilter(defaultFilter);
}
// 优先获取单个RPC服务直连地址,如:cn.com.glsx.***Remote.url=dubbo://127.0.0.1:20880
String url = env.getProperty(clazz.getName().concat(".url"));
if (StringUtils.isEmpty(url)) {
// 获取全局RPC服务直连地址,如:ore.dubbo.provider.url=dubbo://127.0.0.1:20880
url = env.getProperty("dubbo.provider.url");
}
reference.setUrl(url);
}
@Override
public ReferenceBuilder<T> timeout(Integer timeout) {
reference.setTimeout(timeout);
return this;
}
@Override
public ReferenceBuilder<T> version(String version) {
reference.setVersion(version);
return this;
}
@Override
public ReferenceBuilder<T> check(Boolean check) {
reference.setCheck(check);
return this;
}
@Override
public ReferenceBuilder<T> url(String url) {
reference.setUrl(url);
return this;
}
@Override
public T build() {
return reference.get();
}
@Override
public ReferenceBuilder<T> group(String group) {
reference.setGroup(group);
return this;
}
@Override
public ReferenceBuilder<T> retries(Integer retries) {
reference.setRetries(retries);
return this;
}
@Override
public ReferenceBuilder<T> protocol(String protocol) {
reference.setProtocol(protocol);
return this;
}
@Override
public ReferenceBuilder<T> connections(Integer connections) {
reference.setConnections(connections);
return this;
}
@Override
public ReferenceBuilder<T> loadbalance(String loadbalance) {
reference.setLoadbalance(loadbalance);
return this;
}
@Override
public ReferenceBuilder<T> async(Boolean async) {
reference.setAsync(async);
return this;
}
@Override
public ReferenceBuilder<T> proxy(String proxy) {
reference.setProxy(proxy);
return this;
}
@Override
public ReferenceBuilder<T> actives(Integer actives) {
reference.setActives(actives);
return this;
}
@Override
public ReferenceBuilder<T> method(MethodConfig method) {
List<MethodConfig> methods = reference.getMethods();
if (methods == null) {
methods = new ArrayList<MethodConfig>();
}
methods.add(method);
return methods(methods);
}
@Override
public ReferenceBuilder<T> methods(List<MethodConfig> methods) {
reference.setMethods(methods);
return this;
}
@Override
public ReferenceBuilder<T> filter(String filterName) {
reference.setFilter(filterName);
return this;
}
@Override
public ReferenceBuilder<T> client(String client) {
reference.setClient(client);
return this;
}
@Override
public ReferenceBuilder<T> registry(RegistryConfig registry) {
reference.setRegistry(registry);
return this;
}
@Override
public ReferenceBuilder<T> tag(String tagName) {
reference.setTag(tagName);
return this;
}
}
public String getDefaultFilter() {
return defaultFilter;
}
public void setDefaultFilter(String defaultFilter) {
this.defaultFilter = defaultFilter;
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!