1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

sync & commit in greenwich

This commit is contained in:
fangjian0423
2019-10-29 14:57:54 +08:00
parent 12b9091583
commit 980bc3fd7a
94 changed files with 2633 additions and 780 deletions

View File

@@ -13,30 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.dubbo.autoconfigure;
import java.util.*;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.core.type.MethodMetadata;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.alibaba.cloud.dubbo.annotation.DubboTransported;
import com.alibaba.cloud.dubbo.client.loadbalancer.DubboMetadataInitializerInterceptor;
@@ -46,9 +30,33 @@ import com.alibaba.cloud.dubbo.metadata.resolver.DubboTransportedAttributesResol
import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory;
import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor;
import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.core.type.MethodMetadata;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
/**
* Dubbo Auto-{@link Configuration} for {@link LoadBalanced @LoadBalanced}
* {@link RestTemplate}
* {@link RestTemplate}.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
@@ -56,8 +64,8 @@ import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
@ConditionalOnClass(name = { "org.springframework.web.client.RestTemplate" })
@AutoConfigureAfter(name = {
"org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration" })
public class DubboLoadBalancedRestTemplateAutoConfiguration
implements BeanClassLoaderAware, SmartInitializingSingleton {
public class DubboLoadBalancedRestTemplateAutoConfiguration implements
BeanClassLoaderAware, ApplicationContextAware, SmartInitializingSingleton {
private static final Class<DubboTransported> DUBBO_TRANSPORTED_CLASS = DubboTransported.class;
@@ -89,19 +97,21 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration
@Autowired(required = false)
private Map<String, RestTemplate> restTemplates = Collections.emptyMap();
@Nullable
private ApplicationContext applicationContext;
private ClassLoader classLoader;
/**
* The {@link ClientHttpRequestInterceptor} bean that may be
* {@link LoadBalancerInterceptor} or {@link RetryLoadBalancerInterceptor}
* {@link LoadBalancerInterceptor} or {@link RetryLoadBalancerInterceptor}.
*/
private ClientHttpRequestInterceptor loadBalancerInterceptorBean;
@Override
public void afterSingletonsInstantiated() {
loadBalancerInterceptorBean = retryLoadBalancerInterceptor != null
? retryLoadBalancerInterceptor
: loadBalancerInterceptor;
? retryLoadBalancerInterceptor : loadBalancerInterceptor;
}
/**
@@ -109,28 +119,31 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration
* {@link LoadBalanced @LoadBalanced} and {@link LoadBalanced @LoadBalanced} when
* Spring Boot application started (after the callback of
* {@link SmartInitializingSingleton} beans or
* {@link RestTemplateCustomizer#customize(RestTemplate) customization})
* {@link RestTemplateCustomizer#customize(RestTemplate) customization}).
* @param event spring event
*/
@EventListener(ApplicationStartedEvent.class)
public void adaptRestTemplates() {
@EventListener(ContextRefreshedEvent.class)
public void adaptRestTemplates(ContextRefreshedEvent event) {
DubboTransportedAttributesResolver attributesResolver = new DubboTransportedAttributesResolver(
environment);
if (event.getApplicationContext() == this.applicationContext) {
for (Map.Entry<String, RestTemplate> entry : restTemplates.entrySet()) {
String beanName = entry.getKey();
Map<String, Object> dubboTranslatedAttributes = getDubboTranslatedAttributes(
beanName, attributesResolver);
if (!CollectionUtils.isEmpty(dubboTranslatedAttributes)) {
adaptRestTemplate(entry.getValue(), dubboTranslatedAttributes);
DubboTransportedAttributesResolver attributesResolver = new DubboTransportedAttributesResolver(
environment);
for (Map.Entry<String, RestTemplate> entry : restTemplates.entrySet()) {
String beanName = entry.getKey();
Map<String, Object> dubboTranslatedAttributes = getDubboTranslatedAttributes(
beanName, attributesResolver);
if (!CollectionUtils.isEmpty(dubboTranslatedAttributes)) {
adaptRestTemplate(entry.getValue(), dubboTranslatedAttributes);
}
}
}
}
/**
* Gets the annotation attributes {@link RestTemplate} bean being annotated
* {@link DubboTransported @DubboTransported}
*
* {@link DubboTransported @DubboTransported}.
* @param beanName the bean name of {@link LoadBalanced @LoadBalanced}
* {@link RestTemplate}
* @param attributesResolver {@link DubboTransportedAttributesResolver}
@@ -144,10 +157,10 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration
AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition;
MethodMetadata factoryMethodMetadata = annotatedBeanDefinition
.getFactoryMethodMetadata();
attributes = factoryMethodMetadata != null
? Optional.ofNullable(factoryMethodMetadata
.getAnnotationAttributes(DUBBO_TRANSPORTED_CLASS_NAME)).orElse(attributes)
: Collections.emptyMap();
attributes = factoryMethodMetadata != null ? Optional
.ofNullable(factoryMethodMetadata
.getAnnotationAttributes(DUBBO_TRANSPORTED_CLASS_NAME))
.orElse(attributes) : Collections.emptyMap();
}
return attributesResolver.resolve(attributes);
}
@@ -155,7 +168,6 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration
/**
* Adapt the instance of {@link DubboTransporterInterceptor} to the
* {@link LoadBalancerInterceptor} Bean.
*
* @param restTemplate {@link LoadBalanced @LoadBalanced} {@link RestTemplate} Bean
* @param dubboTranslatedAttributes the annotation dubboTranslatedAttributes
* {@link RestTemplate} bean being annotated
@@ -188,4 +200,9 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration
this.classLoader = classLoader;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}

View File

@@ -16,23 +16,12 @@
package com.alibaba.cloud.dubbo.autoconfigure;
import java.util.Collection;
import java.util.Optional;
import java.util.function.Supplier;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.context.event.ServiceBeanExportedEvent;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import com.alibaba.cloud.dubbo.metadata.DubboProtocolConfigSupplier;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.metadata.repository.MetadataServiceInstanceSelector;
import com.alibaba.cloud.dubbo.metadata.resolver.DubboServiceBeanMetadataResolver;
import com.alibaba.cloud.dubbo.metadata.resolver.MetadataResolver;
import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
@@ -42,6 +31,20 @@ import com.alibaba.cloud.dubbo.service.IntrospectiveDubboMetadataService;
import com.alibaba.cloud.dubbo.util.JSONUtils;
import feign.Contract;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.context.event.ServiceBeanExportedEvent;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.util.CollectionUtils;
/**
* Spring Boot Auto-Configuration class for Dubbo Metadata
@@ -68,6 +71,14 @@ public class DubboMetadataAutoConfiguration {
return new DubboServiceBeanMetadataResolver(contract);
}
@Bean
@ConditionalOnMissingBean
public MetadataServiceInstanceSelector metadataServiceInstanceSelector() {
return serviceInstances -> CollectionUtils.isEmpty(serviceInstances)
? Optional.empty()
: serviceInstances.stream().findAny();
}
@Bean
public Supplier<ProtocolConfig> dubboProtocolConfigSupplier(
ObjectProvider<Collection<ProtocolConfig>> protocols) {

View File

@@ -39,6 +39,9 @@ import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
@Configuration
public class DubboOpenFeignAutoConfiguration {
/**
* OpenFeign Targeter class name.
*/
public static final String TARGETER_CLASS_NAME = "org.springframework.cloud.openfeign.Targeter";
@Bean

View File

@@ -105,10 +105,19 @@ import com.netflix.discovery.shared.Applications;
DubboServiceRegistrationAutoConfiguration.class })
public class DubboServiceDiscoveryAutoConfiguration {
/**
* ZookeeperDiscoveryAutoConfiguration.
*/
public static final String ZOOKEEPER_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration";
/**
* ConsulDiscoveryClientConfiguration.
*/
public static final String CONSUL_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "org.springframework.cloud.consul.discovery.ConsulDiscoveryClientConfiguration";
/**
* NacosDiscoveryAutoConfiguration.
*/
public static final String NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration";
private final DubboServiceMetadataRepository dubboServiceMetadataRepository;

View File

@@ -73,8 +73,7 @@ public class RequestMetadata {
}
/**
* Get the best matched {@link RequestMetadata} via specified {@link RequestMetadata}
*
* Get the best matched {@link RequestMetadata} via specified {@link RequestMetadata}.
* @param requestMetadataMap the source of {@link NavigableMap}
* @param requestMetadata the match object
* @return if not matched, return <code>null</code>

View File

@@ -27,7 +27,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Method Request Metadata
* Method Request Metadata.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/

View File

@@ -21,7 +21,7 @@ import java.util.Set;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* Service Rest Metadata
* Service Rest Metadata.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @see RestMethodMetadata

View File

@@ -88,13 +88,13 @@ public class DubboServiceMetadataRepository
/**
* The {@link URL URLs} property name of {@link DubboMetadataService} :
* "dubbo.metadata-service.urls"
* "dubbo.metadata-service.urls".
*/
public static final String DUBBO_METADATA_SERVICE_URLS_PROPERTY_NAME = DUBBO_METADATA_SERVICE_PREFIX
+ "urls";
/**
* The {@link String#format(String, Object...) pattern} of dubbo protocols port
* The {@link String#format(String, Object...) pattern} of dubbo protocols port.
*/
public static final String DUBBO_PROTOCOLS_PORT_PROPERTY_NAME_PATTERN = "dubbo.protocols.%s.port";
@@ -103,17 +103,19 @@ public class DubboServiceMetadataRepository
private final ObjectMapper objectMapper = new ObjectMapper();
/**
* Monitor object for synchronization
* Monitor object for synchronization.
*/
private final Object monitor = new Object();
/**
* A {@link Set} of service names that had been initialized
* A {@link Set} of service names that had been initialized.
*/
private final Set<String> initializedServices = new LinkedHashSet<>();
/**
* All exported {@link URL urls} {@link Map} whose key is the return value of
* {@link URL#getServiceKey()} method and value is the {@link List} of {@link URL
* URLs}
* URLs}.
*/
private final MultiValueMap<String, URL> allExportedURLs = new LinkedMultiValueMap<>();
@@ -122,7 +124,7 @@ public class DubboServiceMetadataRepository
/**
* The subscribed {@link URL urls} {@link Map} of {@link DubboMetadataService}, whose
* key is the return value of {@link URL#getServiceKey()} method and value is the
* {@link List} of {@link URL URLs}
* {@link List} of {@link URL URLs}.
*/
private final MultiValueMap<String, URL> subscribedDubboMetadataServiceURLs = new LinkedMultiValueMap<>();
@@ -145,8 +147,10 @@ public class DubboServiceMetadataRepository
// =================================== REST Metadata
// ================================== //
private volatile Set<String> subscribedServices = emptySet();
/**
* Key is application name Value is Map<RequestMetadata, DubboRestServiceMetadata>
* Key is application name Value is Map&lt;RequestMetadata,
* DubboRestServiceMetadata&gt;.
*/
private Map<String, Map<RequestMetadataMatcher, DubboRestServiceMetadata>> dubboRestServiceMetadataRepository = newHashMap();
@@ -165,6 +169,9 @@ public class DubboServiceMetadataRepository
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private MetadataServiceInstanceSelector metadataServiceInstanceSelector;
@Autowired
private JSONUtils jsonUtils;
@@ -199,9 +206,8 @@ public class DubboServiceMetadataRepository
}
/**
* Initialize {@link #subscribedServices the subscribed services}
*
* @return
* Initialize {@link #subscribedServices the subscribed services}.
* @return stream of subscribed services
*/
@PostConstruct
public Stream<String> initSubscribedServices() {
@@ -253,7 +259,7 @@ public class DubboServiceMetadataRepository
}
/**
* Initialize the metadata
* Initialize the metadata.
*/
private void initializeMetadata() {
doGetSubscribedServices().forEach(this::initializeMetadata);
@@ -263,7 +269,8 @@ public class DubboServiceMetadataRepository
}
/**
* Initialize the metadata of Dubbo Services
* Initialize the metadata of Dubbo Services.
* @param serviceName service of name
*/
public void initializeMetadata(String serviceName) {
synchronized (monitor) {
@@ -281,9 +288,7 @@ public class DubboServiceMetadataRepository
serviceName);
}
// Keep the order in following invocations
initSubscribedDubboMetadataService(serviceName);
initDubboRestServiceMetadataRepository(serviceName);
// mark this service name having been initialized
initializedServices.add(serviceName);
}
@@ -291,7 +296,7 @@ public class DubboServiceMetadataRepository
}
/**
* Remove the metadata of Dubbo Services if no there is no service instance
* Remove the metadata of Dubbo Services if no there is no service instance.
* @param serviceName the service name
*/
public void removeInitializedService(String serviceName) {
@@ -301,8 +306,7 @@ public class DubboServiceMetadataRepository
}
/**
* Get the metadata {@link Map} of {@link DubboMetadataService}
*
* Get the metadata {@link Map} of {@link DubboMetadataService}.
* @return non-null read-only {@link Map}
*/
public Map<String, String> getDubboMetadataServiceMetadata() {
@@ -342,8 +346,7 @@ public class DubboServiceMetadataRepository
}
/**
* Get the property name of Dubbo Protocol
*
* Get the property name of Dubbo Protocol.
* @param protocol Dubbo Protocol
* @return non-null
*/
@@ -352,8 +355,7 @@ public class DubboServiceMetadataRepository
}
/**
* Publish the {@link Set} of {@link ServiceRestMetadata}
*
* Publish the {@link Set} of {@link ServiceRestMetadata}.
* @param serviceRestMetadataSet the {@link Set} of {@link ServiceRestMetadata}
*/
public void publishServiceRestMetadata(
@@ -366,8 +368,7 @@ public class DubboServiceMetadataRepository
}
/**
* Get the {@link Set} of {@link ServiceRestMetadata}
*
* Get the {@link Set} of {@link ServiceRestMetadata}.
* @return non-null read-only {@link Set}
*/
public Set<ServiceRestMetadata> getServiceRestMetadata() {
@@ -396,10 +397,9 @@ public class DubboServiceMetadataRepository
}
/**
* The specified service is subscribe or not
*
* The specified service is subscribe or not.
* @param serviceName the service name
* @return
* @return subscribe or not
*/
public boolean isSubscribedService(String serviceName) {
return doGetSubscribedServices().contains(serviceName);
@@ -431,7 +431,6 @@ public class DubboServiceMetadataRepository
/**
* Get all exported {@link URL urls}.
*
* @return non-null read-only
*/
public Map<String, List<URL>> getAllExportedUrls() {
@@ -439,8 +438,7 @@ public class DubboServiceMetadataRepository
}
/**
* Get all exported {@link URL#getServiceKey() service keys}
*
* Get all exported {@link URL#getServiceKey() service keys}.
* @return non-null read-only
*/
public Set<String> getAllServiceKeys() {
@@ -449,8 +447,7 @@ public class DubboServiceMetadataRepository
/**
* Get the {@link URL urls} that {@link DubboMetadataService} exported by the
* specified {@link ServiceInstance}
*
* specified {@link ServiceInstance}.
* @param serviceInstance {@link ServiceInstance}
* @return the mutable {@link URL urls}
*/
@@ -475,8 +472,7 @@ public class DubboServiceMetadataRepository
}
/**
* Initialize the specified service's {@link ServiceRestMetadata}
*
* Initialize the specified service's {@link ServiceRestMetadata}.
* @param serviceName the service name
*/
protected void initDubboRestServiceMetadataRepository(String serviceName) {
@@ -521,8 +517,7 @@ public class DubboServiceMetadataRepository
/**
* Get a {@link DubboRestServiceMetadata} by the specified service name if
* {@link RequestMetadata} matched
*
* {@link RequestMetadata} matched.
* @param serviceName service name
* @param requestMetadata {@link RequestMetadata} to be matched
* @return {@link DubboRestServiceMetadata} if matched, or <code>null</code>
@@ -618,7 +613,7 @@ public class DubboServiceMetadataRepository
}
protected void initSubscribedDubboMetadataService(String serviceName) {
discoveryClient.getInstances(serviceName).stream().findAny()
metadataServiceInstanceSelector.choose(discoveryClient.getInstances(serviceName))
.map(this::getDubboMetadataServiceURLs)
.ifPresent(dubboMetadataServiceURLs -> {
dubboMetadataServiceURLs.forEach(dubboMetadataServiceURL -> {
@@ -634,6 +629,7 @@ public class DubboServiceMetadataRepository
}
});
});
initDubboRestServiceMetadataRepository(serviceName);
}
private void initSubscribedDubboMetadataServiceURL(URL dubboMetadataServiceURL) {
@@ -649,8 +645,9 @@ public class DubboServiceMetadataRepository
dubboMetadataConfigServiceProxy.initProxy(serviceName, version);
}
public void removeServiceMetadata(String serviceName) {
public void removeMetadata(String serviceName) {
dubboRestServiceMetadataRepository.remove(serviceName);
subscribedDubboMetadataServiceURLs.remove(serviceName);
}
@Override
@@ -658,4 +655,5 @@ public class DubboServiceMetadataRepository
ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2013-2018 the original author or authors.
*
* Licensed 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
*
* https://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.
*/
package com.alibaba.cloud.dubbo.metadata.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.cloud.client.ServiceInstance;
/**
* metadata service instance selector.
*
* @author <a href="mailto:liuxx-u@outlook.com">liuxx</a>
*/
public interface MetadataServiceInstanceSelector {
/**
* choose a service instance to get metadata.
* @param serviceInstances all service instance
* @return the service instance to get metadata
*/
Optional<ServiceInstance> choose(List<ServiceInstance> serviceInstances);
}

View File

@@ -59,7 +59,7 @@ public class DubboServiceBeanMetadataResolver
private ClassLoader classLoader;
/**
* Feign Contracts
* Feign Contracts.
*/
private Collection<Contract> contracts;
@@ -153,9 +153,8 @@ public class DubboServiceBeanMetadataResolver
* Select feign contract methods
* <p>
* extract some code from
* {@link Contract.BaseContract#parseAndValidatateMetadata(java.lang.Class)}
*
* @param targetType
* {@link Contract.BaseContract#parseAndValidatateMetadata(java.lang.Class)}.
* @param targetType class of type
* @return non-null
*/
private List<Method> selectFeignContractMethods(Class<?> targetType) {

View File

@@ -23,25 +23,24 @@ import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata;
import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata;
/**
* The REST metadata resolver
* The REST metadata resolver.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public interface MetadataResolver {
/**
* Resolve the {@link ServiceRestMetadata} {@link Set set} from {@link ServiceBean}
*
* Resolve the {@link ServiceRestMetadata} {@link Set set} from {@link ServiceBean}.
* @param serviceBean {@link ServiceBean}
* @return non-null {@link Set}
*/
Set<ServiceRestMetadata> resolveServiceRestMetadata(ServiceBean serviceBean);
/**
* Resolve {@link RestMethodMetadata} {@link Set set} from {@link Class target type}
*
* Resolve {@link RestMethodMetadata} {@link Set set} from {@link Class target type}.
* @param targetType {@link Class target type}
* @return non-null {@link Set}
*/
Set<RestMethodMetadata> resolveMethodRestMetadata(Class<?> targetType);
}

View File

@@ -13,8 +13,36 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.dubbo.registry;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent;
import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
import com.alibaba.cloud.dubbo.service.DubboMetadataService;
import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy;
import com.alibaba.cloud.dubbo.util.JSONUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.support.FailbackRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.apache.dubbo.common.URLBuilder.from;
@@ -27,56 +55,31 @@ import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL
import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL;
import static org.springframework.util.StringUtils.hasText;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.support.FailbackRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent;
import com.alibaba.cloud.dubbo.service.DubboMetadataService;
import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy;
import com.alibaba.cloud.dubbo.util.JSONUtils;
/**
* Abstract Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration
* abstraction, whose protocol is "spring-cloud"
* abstraction, whose protocol is "spring-cloud".
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
/**
* The parameter name of {@link #servicesLookupInterval}
* The parameter name of {@link #servicesLookupInterval}.
*/
public static final String SERVICES_LOOKUP_INTERVAL_PARAM_NAME = "dubbo.services.lookup.interval";
protected static final String DUBBO_METADATA_SERVICE_CLASS_NAME = DubboMetadataService.class
.getName();
/**
* Caches the IDs of {@link ApplicationListener}
* Caches the IDs of {@link ApplicationListener}.
*/
private static final Set<String> registerListeners = new HashSet<>();
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* The interval in second of lookup service names(only for Dubbo-OPS)
* The interval in second of lookup service names(only for Dubbo-OPS).
*/
private final long servicesLookupInterval;
@@ -88,12 +91,15 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
private final JSONUtils jsonUtils;
private final DubboGenericServiceFactory dubboGenericServiceFactory;
private final ConfigurableApplicationContext applicationContext;
public AbstractSpringCloudRegistry(URL url, DiscoveryClient discoveryClient,
DubboServiceMetadataRepository dubboServiceMetadataRepository,
DubboMetadataServiceProxy dubboMetadataConfigServiceProxy,
JSONUtils jsonUtils, ConfigurableApplicationContext applicationContext) {
JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory,
ConfigurableApplicationContext applicationContext) {
super(url);
this.servicesLookupInterval = url
.getParameter(SERVICES_LOOKUP_INTERVAL_PARAM_NAME, 60L);
@@ -101,6 +107,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
this.repository = dubboServiceMetadataRepository;
this.dubboMetadataConfigServiceProxy = dubboMetadataConfigServiceProxy;
this.jsonUtils = jsonUtils;
this.dubboGenericServiceFactory = dubboGenericServiceFactory;
this.applicationContext = applicationContext;
}
@@ -127,8 +134,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
}
/**
* The sub-type should implement to register
*
* The sub-type should implement to register.
* @param url {@link URL}
*/
protected abstract void doRegister0(URL url);
@@ -142,8 +148,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
}
/**
* The sub-type should implement to unregister
*
* The sub-type should implement to unregister.
* @param url {@link URL}
*/
protected abstract void doUnregister0(URL url);
@@ -171,8 +176,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
/**
* Register a {@link ApplicationListener listener} for
* {@link ServiceInstancesChangedEvent}
*
* {@link ServiceInstancesChangedEvent}.
* @param url {@link URL}
* @param listener {@link NotifyListener}
*/
@@ -221,7 +225,8 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
if (CollectionUtils.isEmpty(serviceInstances)) {
dubboMetadataConfigServiceProxy.removeProxy(serviceName);
repository.removeInitializedService(serviceName);
repository.removeServiceMetadata(serviceName);
repository.removeMetadata(serviceName);
dubboGenericServiceFactory.destroy(serviceName);
if (logger.isWarnEnabled()) {
logger.warn(
"There is no instance from service[name : {}], and then Dubbo Service[key : {}] will not be "
@@ -350,8 +355,8 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
@Override
public final void doUnsubscribe(URL url, NotifyListener listener) {
if (isAdminURL(url)) {
}
// if (isAdminURL(url)) {
// }
}
@Override
@@ -366,4 +371,5 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
protected boolean isDubboMetadataServiceURL(URL url) {
return DUBBO_METADATA_SERVICE_CLASS_NAME.equals(url.getServiceInterface());
}
}

View File

@@ -31,7 +31,7 @@ class DelegatingRegistration implements Registration {
private final ServiceInstance delegate;
public DelegatingRegistration(ServiceInstance delegate) {
DelegatingRegistration(ServiceInstance delegate) {
this.delegate = delegate;
}
@@ -69,4 +69,5 @@ class DelegatingRegistration implements Registration {
public String getScheme() {
return delegate.getScheme();
}
}

View File

@@ -13,20 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.dubbo.registry;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy;
import com.alibaba.cloud.dubbo.util.JSONUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.RegistryFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy;
import com.alibaba.cloud.dubbo.util.JSONUtils;
/**
* Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration abstraction, whose
* protocol is "spring-cloud"
* protocol is "spring-cloud".
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
@@ -37,9 +39,11 @@ public class SpringCloudRegistry extends AbstractSpringCloudRegistry {
public SpringCloudRegistry(URL url, DiscoveryClient discoveryClient,
DubboServiceMetadataRepository dubboServiceMetadataRepository,
DubboMetadataServiceProxy dubboMetadataConfigServiceProxy,
JSONUtils jsonUtils, ConfigurableApplicationContext applicationContext) {
JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory,
ConfigurableApplicationContext applicationContext) {
super(url, discoveryClient, dubboServiceMetadataRepository,
dubboMetadataConfigServiceProxy, jsonUtils, applicationContext);
dubboMetadataConfigServiceProxy, jsonUtils, dubboGenericServiceFactory,
applicationContext);
this.dubboServiceMetadataRepository = dubboServiceMetadataRepository;
}
@@ -52,4 +56,5 @@ public class SpringCloudRegistry extends AbstractSpringCloudRegistry {
protected void doUnregister0(URL url) {
dubboServiceMetadataRepository.unexportURL(url);
}
}

View File

@@ -13,23 +13,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.dubbo.registry;
import static java.lang.System.getProperty;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory;
import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy;
import com.alibaba.cloud.dubbo.util.JSONUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository;
import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy;
import com.alibaba.cloud.dubbo.util.JSONUtils;
import static java.lang.System.getProperty;
/**
* Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration abstraction, whose
* protocol is "spring-cloud"
* protocol is "spring-cloud".
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @see RegistryFactory
@@ -37,8 +39,14 @@ import com.alibaba.cloud.dubbo.util.JSONUtils;
*/
public class SpringCloudRegistryFactory implements RegistryFactory {
/**
* Spring Cloud Protocol.
*/
public static String PROTOCOL = "spring-cloud";
/**
* Spring Cloud Address.
*/
public static String ADDRESS = "localhost";
private static String SERVICES_LOOKUP_SCHEDULER_THREAD_NAME_PREFIX = getProperty(
@@ -55,6 +63,8 @@ public class SpringCloudRegistryFactory implements RegistryFactory {
private JSONUtils jsonUtils;
private DubboGenericServiceFactory dubboGenericServiceFactory;
private volatile boolean initialized = false;
public SpringCloudRegistryFactory() {
@@ -75,6 +85,8 @@ public class SpringCloudRegistryFactory implements RegistryFactory {
this.dubboMetadataConfigServiceProxy = applicationContext
.getBean(DubboMetadataServiceProxy.class);
this.jsonUtils = applicationContext.getBean(JSONUtils.class);
this.dubboGenericServiceFactory = applicationContext
.getBean(DubboGenericServiceFactory.class);
}
@Override
@@ -82,6 +94,7 @@ public class SpringCloudRegistryFactory implements RegistryFactory {
init();
return new SpringCloudRegistry(url, discoveryClient,
dubboServiceMetadataRepository, dubboMetadataConfigServiceProxy,
jsonUtils, applicationContext);
jsonUtils, dubboGenericServiceFactory, applicationContext);
}
}

View File

@@ -38,7 +38,6 @@ public class SubscribedServicesChangedEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param source the object on which the event initially occurred (never {@code null})
* @param oldSubscribedServices the subscribed services before changed
* @param newSubscribedServices the subscribed services after changed

View File

@@ -13,23 +13,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.dubbo.service;
import static java.util.Collections.emptyMap;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.springframework.util.StringUtils.commaDelimitedListToStringArray;
package com.alibaba.cloud.dubbo.service;
import java.beans.PropertyEditorSupport;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.PreDestroy;
import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata;
import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.RegistryConfig;
@@ -37,6 +37,7 @@ import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.rpc.service.GenericService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
@@ -44,11 +45,13 @@ import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.DataBinder;
import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata;
import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata;
import static java.util.Collections.emptyMap;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.springframework.util.StringUtils.commaDelimitedListToStringArray;
/**
* Dubbo {@link GenericService} Factory
* Dubbo {@link GenericService} Factory.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
@@ -56,7 +59,7 @@ public class DubboGenericServiceFactory {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final ConcurrentMap<Integer, ReferenceBean<GenericService>> cache = new ConcurrentHashMap<>();
private final ConcurrentMap<String, ReferenceBean<GenericService>> cache = new ConcurrentHashMap<>();
@Autowired
private ObjectProvider<List<RegistryConfig>> registryConfigs;
@@ -95,12 +98,13 @@ public class DubboGenericServiceFactory {
Integer key = Objects.hash(interfaceName, version, group,
dubboTranslatedAttributes);
return cache.computeIfAbsent(key, k -> {
return cache.computeIfAbsent(group + key, k -> {
ReferenceBean<GenericService> referenceBean = new ReferenceBean<>();
referenceBean.setGeneric(true);
referenceBean.setInterface(interfaceName);
referenceBean.setVersion(version);
referenceBean.setGroup(group);
referenceBean.setCheck(false);
bindReferenceBean(referenceBean, dubboTranslatedAttributes);
return referenceBean;
});
@@ -148,7 +152,17 @@ public class DubboGenericServiceFactory {
@PreDestroy
public void destroy() {
destroyReferenceBeans();
cache.values();
cache.clear();
}
public synchronized void destroy(String serviceName) {
Set<String> removeGroups = new HashSet<>(cache.keySet());
for (String key : removeGroups) {
if (key.contains(serviceName)) {
ReferenceBean<GenericService> referenceBean = cache.remove(key);
referenceBean.destroy();
}
}
}
private void destroyReferenceBeans() {

View File

@@ -24,7 +24,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link DubboMetadataService} {@link InvocationHandler}
* {@link DubboMetadataService} {@link InvocationHandler}.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
@@ -34,7 +34,7 @@ class DubboMetadataServiceInvocationHandler implements InvocationHandler {
private final GenericService genericService;
public DubboMetadataServiceInvocationHandler(String serviceName, String version,
DubboMetadataServiceInvocationHandler(String serviceName, String version,
DubboGenericServiceFactory dubboGenericServiceFactory) {
this.genericService = dubboGenericServiceFactory.create(serviceName,
DubboMetadataService.class, version);
@@ -60,4 +60,5 @@ class DubboMetadataServiceInvocationHandler implements InvocationHandler {
return Stream.of(parameterTypes).map(Class::getName)
.toArray(length -> new String[length]);
}
}

View File

@@ -15,23 +15,25 @@
*/
package com.alibaba.cloud.dubbo.service;
import static java.lang.reflect.Proxy.newProxyInstance;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.DisposableBean;
import static java.lang.reflect.Proxy.newProxyInstance;
/**
* The proxy of {@link DubboMetadataService}
* The proxy of {@link DubboMetadataService}.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public class DubboMetadataServiceProxy implements BeanClassLoaderAware, DisposableBean {
private final DubboGenericServiceFactory dubboGenericServiceFactory;
private final Map<String, DubboMetadataService> dubboMetadataServiceCache = new ConcurrentHashMap<>();
private ClassLoader classLoader;
public DubboMetadataServiceProxy(
@@ -40,8 +42,7 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab
}
/**
* Initializes {@link DubboMetadataService}'s Proxy
*
* Initializes {@link DubboMetadataService}'s Proxy.
* @param serviceName the service name
* @param version the service version
* @return a {@link DubboMetadataService} proxy
@@ -52,7 +53,7 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab
}
/**
* Remove {@link DubboMetadataService}'s Proxy by service name
* Remove {@link DubboMetadataService}'s Proxy by service name.
* @param serviceName the service name
*/
public void removeProxy(String serviceName) {
@@ -60,8 +61,8 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab
}
/**
* Get a proxy instance of {@link DubboMetadataService} via the specified service name
*
* Get a proxy instance of {@link DubboMetadataService} via the specified service
* name.
* @param serviceName the service name
* @return a {@link DubboMetadataService} proxy
*/
@@ -80,8 +81,8 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab
}
/**
* New a proxy instance of {@link DubboMetadataService} via the specified service name
*
* New a proxy instance of {@link DubboMetadataService} via the specified service
* name.
* @param serviceName the service name
* @param version the service version
* @return a {@link DubboMetadataService} proxy
@@ -92,4 +93,5 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab
new DubboMetadataServiceInvocationHandler(serviceName, version,
dubboGenericServiceFactory));
}
}

View File

@@ -15,13 +15,14 @@
*/
package com.alibaba.cloud.dubbo.service.parameter;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.core.Ordered;
import com.alibaba.cloud.dubbo.http.HttpServerRequest;
import com.alibaba.cloud.dubbo.metadata.MethodParameterMetadata;
import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.core.Ordered;
/**
* Dubbo {@link GenericService} Parameter Resolver
*
@@ -31,8 +32,10 @@ public interface DubboGenericServiceParameterResolver extends Ordered {
/**
* Resolves a method parameter into an argument value from a given request.
*
* @return
* @param restMethodMetadata method request metadata
* @param methodParameterMetadata metadata of method
* @param request Http server request
* @return the result of resolve
*/
Object resolve(RestMethodMetadata restMethodMetadata,
MethodParameterMetadata methodParameterMetadata, HttpServerRequest request);