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

Polish : spring-cloud-incubator/spring-cloud-alibaba#409 : Register the Dubbo REST services as Spring Cloud services in non-web environment

This commit is contained in:
mercyblitz
2019-03-08 14:54:33 +08:00
parent 82d0ff2daf
commit 10f06bec1e
26 changed files with 597 additions and 177 deletions

View File

@@ -91,7 +91,6 @@
<optional>true</optional>
</dependency>
<!-- Eureka Service Discovery -->
<dependency>
<groupId>org.springframework.cloud</groupId>
@@ -151,8 +150,7 @@
<!-- Spring Cloud Open Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<optional>true</optional>
<artifactId>spring-cloud-openfeign-core</artifactId>
</dependency>
<!-- Dubbo -->

View File

@@ -16,6 +16,7 @@
*/
package org.springframework.cloud.alibaba.dubbo.autoconfigure;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ServiceConfig;
@@ -26,17 +27,29 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.alibaba.dubbo.metadata.resolver.MetadataResolver;
import org.springframework.cloud.alibaba.dubbo.registry.RegistrationFactory;
import org.springframework.cloud.alibaba.dubbo.service.DubboMetadataConfigService;
import org.springframework.cloud.alibaba.dubbo.service.PublishingDubboMetadataConfigService;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import static org.springframework.cloud.alibaba.dubbo.autoconfigure.DubboMetadataAutoConfiguration.METADATA_PROTOCOL_BEAN_NAME;
/**
@@ -63,6 +76,9 @@ public class DubboMetadataEventHandlingAutoConfiguration {
@Qualifier(METADATA_PROTOCOL_BEAN_NAME)
private ProtocolConfig metadataProtocolConfig;
@Autowired
private ConfigurableApplicationContext context;
@Value("${spring.application.name:application}")
private String currentApplicationName;
@@ -71,10 +87,44 @@ public class DubboMetadataEventHandlingAutoConfiguration {
*/
private ServiceConfig<DubboMetadataConfigService> serviceConfig;
private ServiceInstance restServiceInstance;
@EventListener(ServiceBeanExportedEvent.class)
public void recordRestMetadata(ServiceBeanExportedEvent event) {
public void onServiceBeanExported(ServiceBeanExportedEvent event) {
ServiceBean serviceBean = event.getServiceBean();
dubboMetadataConfigService.publishServiceRestMetadata(metadataResolver.resolveServiceRestMetadata(serviceBean));
publishServiceRestMetadata(serviceBean);
setRestServiceInstance(serviceBean);
}
private void setRestServiceInstance(ServiceBean serviceBean) {
List<URL> urls = serviceBean.getExportedUrls();
urls.stream()
.filter(url -> "rest".equalsIgnoreCase(url.getProtocol()))
.forEach(url -> {
String host = url.getIp();
int port = url.getPort();
if (restServiceInstance == null) {
String instanceId = currentApplicationName + "-" + host + ":" + port;
this.restServiceInstance = new DefaultServiceInstance(instanceId, currentApplicationName,
host, port, false, new HashMap<>());
} else {
if (!host.equals(restServiceInstance.getHost())) {
if (logger.isWarnEnabled()) {
logger.warn("Current application[{}] host is not consistent, expected: {}, actual: {}",
currentApplicationName, restServiceInstance.getHost(), host);
}
}
if (port != restServiceInstance.getPort()) {
if (logger.isWarnEnabled()) {
logger.warn("Current application[{}] port is not consistent, expected: {}, actual: {}",
currentApplicationName, restServiceInstance.getPort(), port);
}
}
}
});
}
@EventListener(ApplicationReadyEvent.class)
@@ -92,6 +142,32 @@ public class DubboMetadataEventHandlingAutoConfiguration {
unexportDubboMetadataConfigService();
}
@ConditionalOnNotWebApplication
@Bean
public ApplicationRunner applicationRunner() {
return args -> {
if (restServiceInstance == null) {
return;
}
// From RegistrationFactoryProvider
RegistrationFactory registrationFactory = context.getBean(RegistrationFactory.class);
ServiceRegistry<Registration> serviceRegistry = context.getBean(ServiceRegistry.class);
Registration registration = context.getBean(Registration.class);
restServiceInstance.getMetadata().putAll(registration.getMetadata());
serviceRegistry.register(registrationFactory.create(restServiceInstance, context));
};
}
private void publishServiceRestMetadata(ServiceBean serviceBean) {
dubboMetadataConfigService.publishServiceRestMetadata(metadataResolver.resolveServiceRestMetadata(serviceBean));
}
private void exportDubboMetadataConfigService() {
if (serviceConfig != null && serviceConfig.isExported()) {

View File

@@ -20,6 +20,7 @@ import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.config.spring.util.PropertySourcesUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.cloud.alibaba.dubbo.registry.RegistrationFactoryProvider;
import org.springframework.cloud.alibaba.dubbo.registry.handler.DubboRegistryServiceIdHandler;
import org.springframework.cloud.alibaba.dubbo.registry.handler.StandardDubboRegistryServiceIdHandler;
import org.springframework.cloud.alibaba.dubbo.service.DubboGenericServiceExecutionContextFactory;
@@ -76,6 +77,11 @@ public class DubboServiceAutoConfiguration {
return new StandardDubboRegistryServiceIdHandler(context);
}
@Bean
public RegistrationFactoryProvider registrationFactoryProvider() {
return new RegistrationFactoryProvider();
}
/**
* Bugfix code for an issue : https://github.com/apache/incubator-dubbo-spring-boot-project/issues/459
*

View File

@@ -37,19 +37,9 @@ public abstract class AbstractRegistrationFactory<R extends Registration> implem
public final R create(URL url, ConfigurableApplicationContext applicationContext) {
ServiceInstance serviceInstance = createServiceInstance(url, applicationContext);
return create(url, applicationContext, serviceInstance);
return create(serviceInstance, applicationContext);
}
/**
* Sub-class should override this method to create an instance of {@link R}
*
* @param url The Dubbo's {@link URL}
* @param applicationContext {@link ConfigurableApplicationContext}
* @param serviceInstance {@link ServiceInstance}
* @return nullable
*/
protected abstract R create(URL url, ConfigurableApplicationContext applicationContext, ServiceInstance serviceInstance);
/**
* Create an instance {@link ServiceInstance}. This method maybe override by sub-class.
*

View File

@@ -16,7 +16,6 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry;
import org.apache.dubbo.common.URL;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.ConfigurableApplicationContext;
@@ -29,7 +28,7 @@ import org.springframework.context.ConfigurableApplicationContext;
public class DefaultRegistrationFactory extends AbstractRegistrationFactory<Registration> {
@Override
protected Registration create(URL url, ConfigurableApplicationContext applicationContext, ServiceInstance serviceInstance) {
public Registration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
return new DelegatingRegistration(serviceInstance);
}
}

View File

@@ -17,6 +17,7 @@
package org.springframework.cloud.alibaba.dubbo.registry;
import org.apache.dubbo.common.URL;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.ConfigurableApplicationContext;
@@ -37,4 +38,13 @@ public interface RegistrationFactory<R extends Registration> {
* @return a instance of {@link R}, if null, it indicates the registration will not be executed.
*/
R create(URL url, ConfigurableApplicationContext applicationContext);
/**
* Create a instance of {@link R}
*
* @param serviceInstance {@link ServiceInstance}
* @param applicationContext {@link ConfigurableApplicationContext}
* @return a instance of {@link R}, if null, it indicates the registration will not be executed.
*/
R create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext);
}

View File

@@ -0,0 +1,144 @@
/*
* 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.
*/
package org.springframework.cloud.alibaba.dubbo.registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.ResolvableType;
import java.util.List;
import static org.springframework.beans.BeanUtils.instantiateClass;
import static org.springframework.core.ResolvableType.forInstance;
import static org.springframework.core.ResolvableType.forType;
import static org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames;
import static org.springframework.util.ClassUtils.isPresent;
import static org.springframework.util.ClassUtils.resolveClassName;
/**
* {@link RegistrationFactory} Provider
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public class RegistrationFactoryProvider implements FactoryBean<RegistrationFactory>, ApplicationContextAware {
private final Logger logger = LoggerFactory.getLogger(getClass());
private RegistrationFactory registrationFactory;
@Override
public RegistrationFactory getObject() throws BeansException {
return registrationFactory;
}
@Override
public Class<?> getObjectType() {
return RegistrationFactory.class;
}
public boolean isSingleton() {
return true;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ServiceRegistry<Registration> serviceRegistry = applicationContext.getBean(ServiceRegistry.class);
ClassLoader classLoader = applicationContext.getClassLoader();
this.registrationFactory = buildRegistrationFactory(serviceRegistry, classLoader);
}
private RegistrationFactory buildRegistrationFactory(ServiceRegistry<Registration> serviceRegistry,
ClassLoader classLoader) {
RegistrationFactory registrationFactory = null;
List<String> factoryClassNames = loadFactoryNames(RegistrationFactory.class, classLoader);
ResolvableType serviceRegistryType = forInstance(serviceRegistry);
// Get first generic Class
Class<?> registrationClass = resolveGenericClass(serviceRegistryType, ServiceRegistry.class, 0);
for (String factoryClassName : factoryClassNames) {
if (isPresent(factoryClassName, classLoader)) { // ignore compilation issue
Class<?> factoryClass = resolveClassName(factoryClassName, classLoader);
ResolvableType registrationFactoryType = forType(factoryClass);
Class<?> actualRegistrationClass = resolveGenericClass(registrationFactoryType, RegistrationFactory.class, 0);
if (registrationClass.equals(actualRegistrationClass)) {
registrationFactory = (RegistrationFactory) instantiateClass(registrationFactoryType.getRawClass());
break;
}
}
}
if (registrationFactory == null) {
if (logger.isWarnEnabled()) {
logger.warn("{} implementation can't be resolved by ServiceRegistry[{}]",
registrationClass.getSimpleName(), serviceRegistry.getClass().getName());
}
registrationFactory = new DefaultRegistrationFactory();
} else {
if (logger.isInfoEnabled()) {
logger.info("{} has been resolved by ServiceRegistry[{}]",
registrationFactory.getClass().getName(), serviceRegistry.getClass().getName());
}
}
return registrationFactory;
}
private Class<?> resolveGenericClass(ResolvableType implementedType, Class<?> interfaceClass, int index) {
ResolvableType resolvableType = implementedType;
try {
OUTER:
while (true) {
ResolvableType[] interfaceTypes = resolvableType.getInterfaces();
for (ResolvableType interfaceType : interfaceTypes) {
if (interfaceType.resolve().equals(interfaceClass)) {
resolvableType = interfaceType;
break OUTER;
}
}
ResolvableType superType = resolvableType.getSuperType();
Class<?> superClass = superType.resolve();
if (Object.class.equals(superClass)) {
break;
}
resolvableType = superType;
}
} catch (Throwable e) {
resolvableType = ResolvableType.forType(void.class);
}
return resolvableType.resolveGeneric(index);
}
}

View File

@@ -26,19 +26,11 @@ import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.ResolvableType;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import static java.lang.System.getProperty;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.springframework.beans.BeanUtils.instantiateClass;
import static org.springframework.core.ResolvableType.forInstance;
import static org.springframework.core.ResolvableType.forType;
import static org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames;
import static org.springframework.util.ClassUtils.isPresent;
import static org.springframework.util.ClassUtils.resolveClassName;
/**
* Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration abstraction, whose protocol is "spring-cloud"
@@ -77,7 +69,7 @@ public class SpringCloudRegistryFactory implements RegistryFactory {
}
this.serviceRegistry = applicationContext.getBean(ServiceRegistry.class);
this.registrationFactory = buildRegistrationFactory(serviceRegistry, applicationContext.getClassLoader());
this.registrationFactory = applicationContext.getBean(RegistrationFactory.class);
this.discoveryClient = applicationContext.getBean(DiscoveryClient.class);
}
@@ -91,80 +83,4 @@ public class SpringCloudRegistryFactory implements RegistryFactory {
public static void setApplicationContext(ConfigurableApplicationContext applicationContext) {
SpringCloudRegistryFactory.applicationContext = applicationContext;
}
private RegistrationFactory buildRegistrationFactory(ServiceRegistry<Registration> serviceRegistry,
ClassLoader classLoader) {
RegistrationFactory registrationFactory = null;
List<String> factoryClassNames = loadFactoryNames(RegistrationFactory.class, classLoader);
ResolvableType serviceRegistryType = forInstance(serviceRegistry);
// Get first generic Class
Class<?> registrationClass = resolveGenericClass(serviceRegistryType, ServiceRegistry.class, 0);
for (String factoryClassName : factoryClassNames) {
if (isPresent(factoryClassName, classLoader)) { // ignore compilation issue
Class<?> factoryClass = resolveClassName(factoryClassName, classLoader);
ResolvableType registrationFactoryType = forType(factoryClass);
Class<?> actualRegistrationClass = resolveGenericClass(registrationFactoryType, RegistrationFactory.class, 0);
if (registrationClass.equals(actualRegistrationClass)) {
registrationFactory = (RegistrationFactory) instantiateClass(registrationFactoryType.getRawClass());
break;
}
}
}
if (registrationFactory == null) {
if (logger.isWarnEnabled()) {
logger.warn("{} implementation can't be resolved by ServiceRegistry[{}]",
registrationClass.getSimpleName(), serviceRegistry.getClass().getName());
}
registrationFactory = new DefaultRegistrationFactory();
} else {
if (logger.isInfoEnabled()) {
logger.info("{} has been resolved by ServiceRegistry[{}]",
registrationFactory.getClass().getName(), serviceRegistry.getClass().getName());
}
}
return registrationFactory;
}
private Class<?> resolveGenericClass(ResolvableType implementedType, Class<?> interfaceClass, int index) {
ResolvableType resolvableType = implementedType;
try {
OUTER:
while (true) {
ResolvableType[] interfaceTypes = resolvableType.getInterfaces();
for (ResolvableType interfaceType : interfaceTypes) {
if (interfaceType.resolve().equals(interfaceClass)) {
resolvableType = interfaceType;
break OUTER;
}
}
ResolvableType superType = resolvableType.getSuperType();
Class<?> superClass = superType.resolve();
if (Object.class.equals(superClass)) {
break;
}
resolvableType = superType;
}
} catch (Throwable e) {
resolvableType = ResolvableType.forType(void.class);
}
return resolvableType.resolveGeneric(index);
}
}

View File

@@ -16,7 +16,6 @@
*/
package org.springframework.cloud.alibaba.dubbo.registry.apache.zookeeper;
import org.apache.dubbo.common.URL;
import org.springframework.cloud.alibaba.dubbo.registry.AbstractRegistrationFactory;
import org.springframework.cloud.alibaba.dubbo.registry.RegistrationFactory;
import org.springframework.cloud.client.ServiceInstance;
@@ -33,7 +32,7 @@ import org.springframework.context.ConfigurableApplicationContext;
public class ZookeeperRegistrationFactory extends AbstractRegistrationFactory<ZookeeperRegistration> {
@Override
protected ZookeeperRegistration create(URL url, ConfigurableApplicationContext applicationContext, ServiceInstance serviceInstance) {
public ZookeeperRegistration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
ZookeeperInstance zookeeperInstance = new ZookeeperInstance(serviceInstance.getInstanceId(),
serviceInstance.getServiceId(), serviceInstance.getMetadata());

View File

@@ -17,7 +17,6 @@
package org.springframework.cloud.alibaba.dubbo.registry.hashicorp.consul;
import com.ecwid.consul.v1.agent.model.NewService;
import org.apache.dubbo.common.URL;
import org.springframework.cloud.alibaba.dubbo.registry.AbstractRegistrationFactory;
import org.springframework.cloud.alibaba.dubbo.registry.RegistrationFactory;
import org.springframework.cloud.client.ServiceInstance;
@@ -40,7 +39,7 @@ import java.util.Set;
public class ConsulRegistrationFactory extends AbstractRegistrationFactory<ConsulRegistration> {
@Override
protected ConsulRegistration create(URL url, ConfigurableApplicationContext applicationContext, ServiceInstance serviceInstance) {
public ConsulRegistration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
Map<String, String> metadata = getMetadata(serviceInstance);
List<String> tags = createTags(metadata);

View File

@@ -18,7 +18,6 @@ package org.springframework.cloud.alibaba.dubbo.registry.netflix.eureka;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.discovery.EurekaClientConfig;
import org.apache.dubbo.common.URL;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.alibaba.dubbo.registry.AbstractRegistrationFactory;
@@ -37,7 +36,7 @@ import org.springframework.context.ConfigurableApplicationContext;
public class EurekaRegistrationFactory extends AbstractRegistrationFactory<EurekaRegistration> {
@Override
protected EurekaRegistration create(URL url, ConfigurableApplicationContext applicationContext, ServiceInstance serviceInstance) {
public EurekaRegistration create(ServiceInstance serviceInstance, ConfigurableApplicationContext applicationContext) {
CloudEurekaInstanceConfig cloudEurekaInstanceConfig = applicationContext.getBean(CloudEurekaInstanceConfig.class);
ObjectProvider<HealthCheckHandler> healthCheckHandler = applicationContext.getBeanProvider(HealthCheckHandler.class);
EurekaClientConfig eurekaClientConfig = applicationContext.getBean(EurekaClientConfig.class);