From 06b2b5f02f99628c2dcef14e7fda24f604860f83 Mon Sep 17 00:00:00 2001 From: liubao68 Date: Wed, 18 Oct 2023 15:57:32 +0800 Subject: [PATCH] [SCB-2813]refactoring configuration extension because can not using ConfigurationProperties before configuration setup (#3976) --- .../rest/TestRestEngineSchemaListener.java | 8 ++ .../definition/TestRestOperationMeta.java | 27 +++-- .../rest/locator/TestMicroservicePaths.java | 27 +++-- .../rest/locator/TestServicePathManager.java | 37 +++--- .../core/ConfigurationSpringInitializer.java | 99 ---------------- .../apache/servicecomb/core/SCBEngine.java | 21 +--- .../core/ServiceCombCoreConfiguration.java | 14 +-- .../core/bootstrap/SCBBootstrap.java | 10 +- .../ServiceCombMicroserviceMeta.java | 5 +- .../core/invocation/InvocationFactory.java | 4 +- .../producer/ProducerBootListener.java | 12 +- .../registry/discovery/SwaggerLoader.java | 13 +- .../servicecomb/demo/edge/business/Impl.java | 12 +- .../servicecomb/demo/edge/business/Impl.java | 10 +- .../servicecomb/demo/edge/business/Impl.java | 12 +- .../demo/edge/consumer/Consumer.java | 8 +- .../consumer/EdgeServiceGovernanceTest.java | 7 +- .../demo/edge/model/ResultWithInstance.java | 7 +- .../demo/CodeFirstRestTemplate.java | 11 +- .../CodeFirstRestTemplateSpringmvc.java | 11 +- .../demo/springmvc/client/TestResponse.java | 15 +-- .../config/apollo/ApolloConfiguration.java | 10 -- .../apollo/ApolloDynamicPropertiesSource.java | 17 +-- ...servicecomb.config.DynamicPropertiesSource | 18 +++ .../config/cc/ConfigCenterConfiguration.java | 11 -- .../ConfigCenterDynamicPropertiesSource.java | 58 ++++----- .../cc/ConfigCenterInformationCollector.java | 12 +- ...servicecomb.config.DynamicPropertiesSource | 18 +++ .../config/kie/KieConfigConfiguration.java | 11 -- .../kie/KieDynamicPropertiesSource.java | 45 +++---- .../KieClientInformationCollector.java | 13 +- ...servicecomb.config.DynamicPropertiesSource | 18 +++ .../servicecomb/config/nacos/NacosClient.java | 12 +- .../nacos/NacosConfigConfiguration.java | 11 -- .../nacos/NacosDynamicPropertiesSource.java | 7 +- ...servicecomb.config.DynamicPropertiesSource | 18 +++ .../config/nacos/NacosClientTest.java | 6 +- .../edge/core/CommonHttpEdgeDispatcher.java | 8 +- .../config/BootStrapProperties.java | 20 ++++ .../ConfigEnvironmentPostProcessor.java | 35 ++++-- .../config/DynamicPropertiesSource.java | 9 +- .../config/FoundationConfigConfiguration.java | 11 -- .../InMemoryDynamicPropertiesSource.java | 5 +- .../LastPropertyPlaceholderConfigurer.java | 39 ------ .../config/MicroserviceProperties.java | 111 ------------------ ...servicecomb.config.DynamicPropertiesSource | 18 +++ .../main/resources/META-INF/spring.factories | 2 +- ...TestLastPropertyPlaceholderConfigurer.java | 69 ----------- ...iorityInstancePropertyDiscoveryFilter.java | 11 +- .../loadbalance/TestLoadBalanceFilter.java | 8 +- ...tyInstancePropertyDiscoveryFilterTest.java | 33 +++--- .../consumer/ConsumerTokenManager.java | 13 +- .../TestAuthenticationBootListener.java | 18 +-- .../provider/TestProviderTokenManager.java | 12 +- .../prometheus/PrometheusPublisher.java | 11 +- .../prometheus/TestPrometheusPublisher.java | 7 +- .../LightWeightRegistryConfiguration.java | 7 +- .../LocalRegistrationInstance.java | 25 ++-- .../LocalRegistryConfiguration.java | 6 +- .../nacos/NacosMicroserviceHandler.java | 13 +- .../registry/nacos/NacosRegistration.java | 21 ++-- .../nacos/NacosRegistrationInstance.java | 17 +-- .../registry/sc/MicroserviceHandler.java | 21 ++-- .../registry/sc/SCAddressManager.java | 7 +- .../registry/sc/SCConfiguration.java | 5 +- .../registry/sc/SCRegistration.java | 11 +- .../solution/basic/health/HealthEndpoint.java | 1 + 67 files changed, 472 insertions(+), 757 deletions(-) delete mode 100644 core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringInitializer.java create mode 100644 dynamic-config/config-apollo/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource create mode 100644 dynamic-config/config-cc/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource create mode 100644 dynamic-config/config-kie/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource create mode 100644 dynamic-config/config-nacos/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource rename core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringBootInitializer.java => foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigEnvironmentPostProcessor.java (80%) delete mode 100644 foundations/foundation-config/src/main/java/org/apache/servicecomb/config/LastPropertyPlaceholderConfigurer.java delete mode 100644 foundations/foundation-config/src/main/java/org/apache/servicecomb/config/MicroserviceProperties.java create mode 100644 foundations/foundation-config/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource rename {core => foundations/foundation-config}/src/main/resources/META-INF/spring.factories (92%) delete mode 100644 foundations/foundation-config/src/test/java/org/apache/servicecomb/config/TestLastPropertyPlaceholderConfigurer.java diff --git a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestRestEngineSchemaListener.java b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestRestEngineSchemaListener.java index 43f452a1498..fa619acb725 100644 --- a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestRestEngineSchemaListener.java +++ b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/TestRestEngineSchemaListener.java @@ -26,6 +26,7 @@ import org.apache.servicecomb.common.rest.locator.OperationLocator; import org.apache.servicecomb.common.rest.locator.ServicePathManager; import org.apache.servicecomb.common.rest.locator.TestPathSchema; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.BootListener; import org.apache.servicecomb.core.SCBEngine; import org.apache.servicecomb.core.bootstrap.SCBBootstrap; @@ -59,6 +60,13 @@ public static void setup() { .thenReturn(false); Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)) + .thenReturn(BootStrapProperties.DEFAULT_APPLICATION); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_NAME)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_NAME); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_ENVIRONMENT)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_ENVIRONMENT); + List listeners = new ArrayList<>(); listeners.add(new RestEngineSchemaListener()); scbEngine.setBootListeners(listeners); diff --git a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/definition/TestRestOperationMeta.java b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/definition/TestRestOperationMeta.java index 7df112fcd00..0e4e30ed944 100644 --- a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/definition/TestRestOperationMeta.java +++ b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/definition/TestRestOperationMeta.java @@ -27,6 +27,7 @@ import java.util.List; import org.apache.servicecomb.common.rest.RestEngineSchemaListener; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.BootListener; import org.apache.servicecomb.core.SCBEngine; import org.apache.servicecomb.core.bootstrap.SCBBootstrap; @@ -35,8 +36,8 @@ import org.apache.servicecomb.core.executor.ExecutorManager; import org.apache.servicecomb.core.transport.TransportManager; import org.hamcrest.MatcherAssert; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.core.env.Environment; @@ -156,25 +157,33 @@ public void formWithView(@FormParam("form") String form) { } } - static SCBEngine scbEngine; + SCBEngine scbEngine; - static OpenAPI swagger; + OpenAPI swagger; OperationMeta meta; RestOperationMeta operationMeta; - @BeforeAll - public static void classSetup() { + @BeforeEach + public void setUp() { Environment environment = Mockito.mock(Environment.class); scbEngine = SCBBootstrap.createSCBEngineForTest(environment); ExecutorManager executorManager = Mockito.mock(ExecutorManager.class); TransportManager transportManager = Mockito.mock(TransportManager.class); scbEngine.setTransportManager(transportManager); scbEngine.setExecutorManager(executorManager); - scbEngine.setEnvironment(environment); + + Mockito.when(environment.getProperty("servicecomb.rest.parameter.decodeAsObject", boolean.class, false)) + .thenReturn(false); Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)) + .thenReturn(BootStrapProperties.DEFAULT_APPLICATION); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_NAME)) + .thenReturn("test"); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_ENVIRONMENT)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_ENVIRONMENT); List listeners = new ArrayList<>(); listeners.add(new RestEngineSchemaListener()); @@ -185,8 +194,8 @@ public static void classSetup() { swagger = Mockito.spy(scbEngine.getProducerMicroserviceMeta().ensureFindSchemaMeta("sid1").getSwagger()); } - @AfterAll - public static void classTeardown() { + @AfterEach + public void teardown() { scbEngine.destroy(); } diff --git a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestMicroservicePaths.java b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestMicroservicePaths.java index 95538da155b..d99fb3b04f1 100644 --- a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestMicroservicePaths.java +++ b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestMicroservicePaths.java @@ -25,31 +25,36 @@ import org.apache.servicecomb.common.rest.RestEngineSchemaListener; import org.apache.servicecomb.common.rest.definition.RestOperationMeta; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.BootListener; import org.apache.servicecomb.core.SCBEngine; import org.apache.servicecomb.core.bootstrap.SCBBootstrap; import org.apache.servicecomb.core.executor.ExecutorManager; import org.apache.servicecomb.core.transport.TransportManager; -import org.apache.servicecomb.foundation.common.LegacyPropertyFactory; import org.apache.servicecomb.foundation.common.exceptions.ServiceCombException; -import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.core.env.Environment; public class TestMicroservicePaths { - static SCBEngine scbEngine; + SCBEngine scbEngine; - static MicroservicePaths paths; + MicroservicePaths paths; - @BeforeAll - public static void setup() { + @BeforeEach + public void setup() { Environment environment = Mockito.mock(Environment.class); scbEngine = SCBBootstrap.createSCBEngineForTest(environment); - LegacyPropertyFactory.setEnvironment(environment); - scbEngine.setEnvironment(environment); + + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)) + .thenReturn(BootStrapProperties.DEFAULT_APPLICATION); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_NAME)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_NAME); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_ENVIRONMENT)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_ENVIRONMENT); Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); Mockito.when(environment.getProperty("servicecomb.rest.parameter.decodeAsObject", boolean.class, false)) @@ -68,8 +73,8 @@ public static void setup() { paths = spm.producerPaths; } - @AfterAll - public static void teardown() { + @AfterEach + public void teardown() { scbEngine.destroy(); } diff --git a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestServicePathManager.java b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestServicePathManager.java index b6fe098c36a..84ae22015ae 100644 --- a/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestServicePathManager.java +++ b/common/common-rest/src/test/java/org/apache/servicecomb/common/rest/locator/TestServicePathManager.java @@ -24,37 +24,43 @@ import java.util.List; import org.apache.servicecomb.common.rest.RestEngineSchemaListener; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.BootListener; import org.apache.servicecomb.core.SCBEngine; import org.apache.servicecomb.core.bootstrap.SCBBootstrap; import org.apache.servicecomb.core.executor.ExecutorManager; import org.apache.servicecomb.core.transport.TransportManager; -import org.apache.servicecomb.foundation.common.LegacyPropertyFactory; import org.apache.servicecomb.foundation.common.utils.ClassLoaderScopeContext; import org.apache.servicecomb.registry.definition.DefinitionConst; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.core.env.Environment; public class TestServicePathManager { - static Environment environment = Mockito.mock(Environment.class); - - @BeforeAll - public static void beforeClass() { - LegacyPropertyFactory.setEnvironment(environment); - Mockito.when(environment.getProperty("servicecomb.rest.parameter.decodeAsObject", boolean.class, false)) - .thenReturn(false); - } - SCBEngine scbEngine; + Environment environment; + @BeforeEach public void setUp() { + environment = Mockito.mock(Environment.class); + scbEngine = SCBBootstrap.createSCBEngineForTest(environment); + Mockito.when(environment.getProperty("servicecomb.rest.parameter.decodeAsObject", boolean.class, false)) + .thenReturn(false); + Mockito.when(environment.getProperty("servicecomb.rest.parameter.decodeAsObject", boolean.class, false)) + .thenReturn(false); + Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, + long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)) + .thenReturn(BootStrapProperties.DEFAULT_APPLICATION); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_NAME)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_NAME); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_ENVIRONMENT)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_ENVIRONMENT); } @AfterEach @@ -65,11 +71,6 @@ public void tearDown() { @Test public void testBuildProducerPathsNoPrefix() { - Environment environment = Mockito.mock(Environment.class); - scbEngine = SCBBootstrap.createSCBEngineForTest(environment); - scbEngine.setEnvironment(environment); - Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, - long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); ExecutorManager executorManager = Mockito.mock(ExecutorManager.class); TransportManager transportManager = Mockito.mock(TransportManager.class); scbEngine.setTransportManager(transportManager); @@ -90,9 +91,7 @@ public void testBuildProducerPathsNoPrefix() { @Test public void testBuildProducerPathsHasPrefix() { ClassLoaderScopeContext.setClassLoaderScopeProperty(DefinitionConst.URL_PREFIX, "/root/rest"); - Environment environment = Mockito.mock(Environment.class); - scbEngine = SCBBootstrap.createSCBEngineForTest(environment); - scbEngine.setEnvironment(environment); + Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); Mockito.when(environment.getProperty(DefinitionConst.REGISTER_URL_PREFIX, boolean.class, false)).thenReturn(false); diff --git a/core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringInitializer.java b/core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringInitializer.java deleted file mode 100644 index 7ab2a29bac1..00000000000 --- a/core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringInitializer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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.apache.servicecomb.core; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -import org.apache.servicecomb.config.DynamicPropertiesSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.EnvironmentAware; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.Environment; - -/** - * Add dynamic configuration, microserive.yaml to spring - */ -public class ConfigurationSpringInitializer extends PropertySourcesPlaceholderConfigurer implements EnvironmentAware { - private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationSpringInitializer.class); - - public static final String MICROSERVICE_PROPERTY_SOURCE_NAME = "microservice.yaml"; - - public static final String MAPPING_PROPERTY_SOURCE_NAME = "mapping.yaml"; - - public static final String EXTERNAL_INIT = "scb-config-external-init"; - - public static void setExternalInit(boolean value) { - System.setProperty(EXTERNAL_INIT, String.valueOf(value)); - } - - public static boolean isExternalInit() { - return Boolean.getBoolean(EXTERNAL_INIT); - } - - private final List> dynamicPropertiesSources; - - public ConfigurationSpringInitializer(List> dynamicPropertiesSources) { - setOrder(Ordered.LOWEST_PRECEDENCE / 2); - setIgnoreUnresolvablePlaceholders(true); - this.dynamicPropertiesSources = dynamicPropertiesSources; - } - - /** - * Get configurations from Spring, merge them into the configurations of ServiceComb. - * @param environment From which to get the extra config. - */ - @Override - public void setEnvironment(Environment environment) { - super.setEnvironment(environment); - if (isExternalInit()) { - return; - } - - addDynamicConfigurationToSpring(environment); - } - - - private void addDynamicConfigurationToSpring(Environment environment) { - if (!(environment instanceof ConfigurableEnvironment)) { - return; - } - try { - for (DynamicPropertiesSource dynamicPropertiesSource : dynamicPropertiesSources) { - ((ConfigurableEnvironment) environment).getPropertySources() - .addFirst(dynamicPropertiesSource.create(environment)); - } - } catch (Exception e) { - if (environment.getProperty(CoreConst.PRINT_SENSITIVE_ERROR_MESSAGE, boolean.class, - false)) { - LOGGER.warn("set up spring property source failed.", e); - } else { - LOGGER.warn("set up spring property source failed. msg: {}", e.getMessage()); - } - } - } - - @Override - protected Properties mergeProperties() throws IOException { - return super.mergeProperties(); - } -} diff --git a/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java b/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java index e63d2a49724..f290379dd2e 100644 --- a/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java +++ b/core/src/main/java/org/apache/servicecomb/core/SCBEngine.java @@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang3.StringUtils; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.priority.PriorityPropertyManager; import org.apache.servicecomb.core.BootListener.BootEvent; import org.apache.servicecomb.core.BootListener.EventType; @@ -112,8 +112,6 @@ public class SCBEngine { private RegistrationManager registrationManager; - private MicroserviceProperties microserviceProperties; - private DiscoveryManager discoveryManager; private Environment environment; @@ -182,11 +180,6 @@ public void setSwaggerLoader(SwaggerLoader swaggerLoader) { this.swaggerLoader = swaggerLoader; } - @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; - } - @Autowired public void setExecutorManager(ExecutorManager executorManager) { this.executorManager = executorManager; @@ -206,11 +199,7 @@ public ApplicationContext getApplicationContext() { } public String getAppId() { - return this.microserviceProperties.getApplication(); - } - - public MicroserviceProperties getMicroserviceProperties() { - return this.microserviceProperties; + return BootStrapProperties.readApplication(environment); } public void setStatus(SCBStatus status) { @@ -398,11 +387,11 @@ private void doRun() throws Exception { } private void createProducerMicroserviceMeta() { - String microserviceName = this.microserviceProperties.getName(); + String microserviceName = BootStrapProperties.readServiceName(environment); producerMicroserviceMeta = new MicroserviceMeta(this, - this.microserviceProperties.getApplication(), microserviceName, false); + BootStrapProperties.readApplication(environment), microserviceName, false); producerMicroserviceMeta.setFilterChain(filterChainsManager.findProducerChain( - this.microserviceProperties.getApplication(), microserviceName)); + BootStrapProperties.readApplication(environment), microserviceName)); producerMicroserviceMeta.setMicroserviceVersionsMeta(new MicroserviceVersionsMeta(this)); } diff --git a/core/src/main/java/org/apache/servicecomb/core/ServiceCombCoreConfiguration.java b/core/src/main/java/org/apache/servicecomb/core/ServiceCombCoreConfiguration.java index 74b8f075f93..93a3d95a3b2 100644 --- a/core/src/main/java/org/apache/servicecomb/core/ServiceCombCoreConfiguration.java +++ b/core/src/main/java/org/apache/servicecomb/core/ServiceCombCoreConfiguration.java @@ -16,10 +16,6 @@ */ package org.apache.servicecomb.core; -import java.util.List; - -import org.apache.servicecomb.config.DynamicPropertiesSource; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.core.bootup.FilterChainCollector; import org.apache.servicecomb.core.bootup.ServiceInformationCollector; import org.apache.servicecomb.core.executor.ExecutorManager; @@ -35,12 +31,6 @@ @Configuration @SuppressWarnings("unused") public class ServiceCombCoreConfiguration { - @Bean - public ConfigurationSpringInitializer configurationSpringInitializer( - List> dynamicPropertiesSources) { - return new ConfigurationSpringInitializer(dynamicPropertiesSources); - } - @Bean public SCBApplicationListener scbApplicationListener(SCBEngine scbEngine) { SCBApplicationListener scbApplicationListener = new SCBApplicationListener(scbEngine); @@ -60,8 +50,8 @@ public ProducerBootListener producerBootListener() { } @Bean - public SwaggerLoader swaggerLoader(MicroserviceProperties microserviceProperties) { - return new SwaggerLoader(microserviceProperties); + public SwaggerLoader swaggerLoader(Environment environment) { + return new SwaggerLoader(environment); } @Bean diff --git a/core/src/main/java/org/apache/servicecomb/core/bootstrap/SCBBootstrap.java b/core/src/main/java/org/apache/servicecomb/core/bootstrap/SCBBootstrap.java index 14a6c65b8a0..d807464822b 100644 --- a/core/src/main/java/org/apache/servicecomb/core/bootstrap/SCBBootstrap.java +++ b/core/src/main/java/org/apache/servicecomb/core/bootstrap/SCBBootstrap.java @@ -19,10 +19,10 @@ import java.util.Collections; import java.util.List; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.core.SCBEngine; import org.apache.servicecomb.core.executor.ExecutorManager; import org.apache.servicecomb.core.transport.TransportManager; +import org.apache.servicecomb.foundation.common.LegacyPropertyFactory; import org.apache.servicecomb.registry.DiscoveryManager; import org.apache.servicecomb.registry.RegistrationManager; import org.apache.servicecomb.registry.discovery.TelnetInstancePing; @@ -30,24 +30,20 @@ public class SCBBootstrap { public static SCBEngine createSCBEngineForTest(Environment environment) { + LegacyPropertyFactory.setEnvironment(environment); RegistrationManager registrationManager = new RegistrationManager(Collections.emptyList()); DiscoveryManager discoveryManager = new DiscoveryManager(Collections.emptyList(), List.of(new TelnetInstancePing())); registrationManager.init(); discoveryManager.init(); - MicroserviceProperties microserviceProperties = new MicroserviceProperties(); - microserviceProperties.setApplication("test"); - microserviceProperties.setName("test"); - microserviceProperties.setVersion("0.0.1"); - SCBEngine result = new SCBEngineForTest(environment); result.setDiscoveryManager(discoveryManager); result.setRegistrationManager(registrationManager); result.setBootListeners(Collections.emptyList()); - result.setMicroserviceProperties(microserviceProperties); result.setBootUpInformationCollectors(Collections.emptyList()); result.setExecutorManager(new ExecutorManager()); result.setTransportManager(new TransportManager()); + result.setEnvironment(environment); return result; } } diff --git a/core/src/main/java/org/apache/servicecomb/core/governance/ServiceCombMicroserviceMeta.java b/core/src/main/java/org/apache/servicecomb/core/governance/ServiceCombMicroserviceMeta.java index 719771d5149..3893e3e4207 100644 --- a/core/src/main/java/org/apache/servicecomb/core/governance/ServiceCombMicroserviceMeta.java +++ b/core/src/main/java/org/apache/servicecomb/core/governance/ServiceCombMicroserviceMeta.java @@ -17,6 +17,7 @@ package org.apache.servicecomb.core.governance; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.SCBEngine; import org.apache.servicecomb.governance.MicroserviceMeta; @@ -29,11 +30,11 @@ public ServiceCombMicroserviceMeta(SCBEngine scbEngine) { @Override public String getName() { - return scbEngine.getMicroserviceProperties().getName(); + return BootStrapProperties.readServiceName(scbEngine.getEnvironment()); } @Override public String getVersion() { - return scbEngine.getMicroserviceProperties().getVersion(); + return BootStrapProperties.readServiceVersion(scbEngine.getEnvironment()); } } diff --git a/core/src/main/java/org/apache/servicecomb/core/invocation/InvocationFactory.java b/core/src/main/java/org/apache/servicecomb/core/invocation/InvocationFactory.java index b0146e8bc55..776fdb32568 100644 --- a/core/src/main/java/org/apache/servicecomb/core/invocation/InvocationFactory.java +++ b/core/src/main/java/org/apache/servicecomb/core/invocation/InvocationFactory.java @@ -19,6 +19,7 @@ import java.util.Map; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.CoreConst; import org.apache.servicecomb.core.Endpoint; import org.apache.servicecomb.core.Invocation; @@ -41,7 +42,8 @@ public static Invocation forConsumer(ReferenceConfig referenceConfig, OperationM } public static Invocation setSrcMicroservice(Invocation invocation) { - invocation.addContext(CoreConst.SRC_MICROSERVICE, SCBEngine.getInstance().getMicroserviceProperties().getName()); + invocation.addContext(CoreConst.SRC_MICROSERVICE, + BootStrapProperties.readServiceName(SCBEngine.getInstance().getEnvironment())); // TODO: hard code registry name here. This is an old feature not for all registry implementations. if (addSourceServiceId()) { invocation.addContext(CoreConst.SRC_SERVICE_ID, diff --git a/core/src/main/java/org/apache/servicecomb/core/provider/producer/ProducerBootListener.java b/core/src/main/java/org/apache/servicecomb/core/provider/producer/ProducerBootListener.java index 78bb7e4c4f4..7dc291157d3 100644 --- a/core/src/main/java/org/apache/servicecomb/core/provider/producer/ProducerBootListener.java +++ b/core/src/main/java/org/apache/servicecomb/core/provider/producer/ProducerBootListener.java @@ -24,7 +24,7 @@ import java.util.concurrent.ExecutorService; import org.apache.commons.io.FileUtils; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.BootListener; import org.apache.servicecomb.core.CoreConst; import org.apache.servicecomb.core.definition.MicroserviceMeta; @@ -50,8 +50,6 @@ public class ProducerBootListener implements BootListener { private RegistrationManager registrationManager; - private MicroserviceProperties microserviceProperties; - private Environment environment; @Autowired @@ -59,11 +57,6 @@ public void setRegistrationManager(RegistrationManager registrationManager) { this.registrationManager = registrationManager; } - @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; - } - @Autowired public void setEnvironment(Environment environment) { this.environment = environment; @@ -83,7 +76,8 @@ public void onAfterTransport(BootEvent event) { OpenAPI swagger = schemaMeta.getSwagger(); String content = SwaggerUtils.swaggerToString(swagger); if (exportToFile) { - exportToFile(String.format(filePath, microserviceProperties.getName(), schemaMeta.getSchemaId()), content); + exportToFile(String.format(filePath, + BootStrapProperties.readServiceName(environment), schemaMeta.getSchemaId()), content); } else { LOGGER.info("generate swagger for {}/{}/{}, swagger: {}", microserviceMeta.getAppId(), diff --git a/core/src/main/java/org/apache/servicecomb/core/registry/discovery/SwaggerLoader.java b/core/src/main/java/org/apache/servicecomb/core/registry/discovery/SwaggerLoader.java index 997b320b393..4273f2925e0 100644 --- a/core/src/main/java/org/apache/servicecomb/core/registry/discovery/SwaggerLoader.java +++ b/core/src/main/java/org/apache/servicecomb/core/registry/discovery/SwaggerLoader.java @@ -23,7 +23,7 @@ import java.util.Optional; import org.apache.commons.io.FilenameUtils; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.foundation.common.concurrent.ConcurrentHashMapEx; import org.apache.servicecomb.foundation.common.utils.JvmUtils; import org.apache.servicecomb.foundation.common.utils.ResourceUtil; @@ -32,6 +32,7 @@ import org.apache.servicecomb.swagger.generator.SwaggerGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.core.env.Environment; import io.swagger.v3.oas.models.OpenAPI; @@ -50,10 +51,10 @@ public class SwaggerLoader { // third key : schemaId private final Map>> apps = new ConcurrentHashMapEx<>(); - private final MicroserviceProperties microserviceProperties; + private final Environment environment; - public SwaggerLoader(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public SwaggerLoader(Environment environment) { + this.environment = environment; } public void registerSwaggersInLocation(String microserviceName, String swaggersLocation) { @@ -78,7 +79,7 @@ public void registerSwaggersInLocation(String microserviceName, String swaggersL } public void registerSwagger(String microserviceName, String schemaId, OpenAPI swagger) { - MicroserviceNameParser parser = new MicroserviceNameParser(microserviceProperties.getApplication(), + MicroserviceNameParser parser = new MicroserviceNameParser(BootStrapProperties.readApplication(environment), microserviceName); registerSwagger(parser.getAppId(), parser.getMicroserviceName(), schemaId, swagger); } @@ -131,7 +132,7 @@ protected OpenAPI loadFromMemory(String appId, String shortName, String schemaId } protected OpenAPI loadFromResource(String appId, String shortName, String schemaId) { - if (appId.equals(microserviceProperties.getApplication())) { + if (appId.equals(BootStrapProperties.readApplication(environment))) { OpenAPI swagger = loadFromResource(String.format("microservices/%s/%s.yaml", shortName, schemaId)); if (swagger != null) { return swagger; diff --git a/demo/demo-edge/business-1-1-0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java b/demo/demo-edge/business-1-1-0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java index 32f9529bf48..38420d285d6 100644 --- a/demo/demo-edge/business-1-1-0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java +++ b/demo/demo-edge/business-1-1-0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java @@ -17,12 +17,12 @@ package org.apache.servicecomb.demo.edge.business; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.demo.edge.model.AppClientDataRsp; import org.apache.servicecomb.demo.edge.model.ChannelRequestBase; import org.apache.servicecomb.demo.edge.model.ResultWithInstance; import org.apache.servicecomb.provider.rest.common.RestSchema; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -30,11 +30,11 @@ @RestSchema(schemaId = "news-v1") @RequestMapping(path = "/business/v1") public class Impl { - private MicroserviceProperties microserviceProperties; + private Environment environment; @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public void setEnvironment(Environment environment) { + this.environment = environment; } @RequestMapping(path = "/channel/news/subscribe", method = RequestMethod.POST) @@ -47,11 +47,11 @@ public AppClientDataRsp subscribeNewsColumn(@RequestBody ChannelRequestBase requ @RequestMapping(path = "/add", method = RequestMethod.GET) public ResultWithInstance add(int x, int y) { - return ResultWithInstance.create(x + y, microserviceProperties); + return ResultWithInstance.create(x + y, environment); } @RequestMapping(path = "/dec", method = RequestMethod.GET) public ResultWithInstance dec(int x, int y) { - return ResultWithInstance.create(x - y, microserviceProperties); + return ResultWithInstance.create(x - y, environment); } } diff --git a/demo/demo-edge/business-1.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java b/demo/demo-edge/business-1.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java index 28ddc4551f0..1e0d1b84bb8 100644 --- a/demo/demo-edge/business-1.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java +++ b/demo/demo-edge/business-1.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java @@ -17,12 +17,12 @@ package org.apache.servicecomb.demo.edge.business; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.demo.edge.model.AppClientDataRsp; import org.apache.servicecomb.demo.edge.model.ChannelRequestBase; import org.apache.servicecomb.demo.edge.model.ResultWithInstance; import org.apache.servicecomb.provider.rest.common.RestSchema; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -30,11 +30,11 @@ @RestSchema(schemaId = "news-v1") @RequestMapping(path = "/business/v1") public class Impl { - private MicroserviceProperties microserviceProperties; + private Environment environment; @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public void setEnvironment(Environment environment) { + this.environment = environment; } @RequestMapping(path = "/channel/news/subscribe", method = RequestMethod.POST) @@ -47,6 +47,6 @@ public AppClientDataRsp subscribeNewsColumn(@RequestBody ChannelRequestBase requ @RequestMapping(path = "/add", method = RequestMethod.GET) public ResultWithInstance add(int x, int y) { - return ResultWithInstance.create(x + y, microserviceProperties); + return ResultWithInstance.create(x + y, environment); } } diff --git a/demo/demo-edge/business-2.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java b/demo/demo-edge/business-2.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java index caab0bc47d2..942133ece03 100644 --- a/demo/demo-edge/business-2.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java +++ b/demo/demo-edge/business-2.0.0/src/main/java/org/apache/servicecomb/demo/edge/business/Impl.java @@ -25,7 +25,6 @@ import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.demo.edge.model.AppClientDataRsp; import org.apache.servicecomb.demo.edge.model.ChannelRequestBase; import org.apache.servicecomb.demo.edge.model.DependTypeA; @@ -34,6 +33,7 @@ import org.apache.servicecomb.demo.edge.model.User; import org.apache.servicecomb.provider.rest.common.RestSchema; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -51,11 +51,11 @@ @RestSchema(schemaId = "news-v2") @RequestMapping(path = "/business/v2") public class Impl { - private MicroserviceProperties microserviceProperties; + private Environment environment; @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public void setEnvironment(Environment environment) { + this.environment = environment; } File tempDir = new File("target/downloadTemp"); @@ -74,12 +74,12 @@ public AppClientDataRsp subscribeNewsColumn(@RequestBody ChannelRequestBase requ @RequestMapping(path = "/add", method = RequestMethod.GET) public ResultWithInstance add(int x, int y) { - return ResultWithInstance.create(x + y, microserviceProperties); + return ResultWithInstance.create(x + y, environment); } @RequestMapping(path = "/dec", method = RequestMethod.GET) public ResultWithInstance dec(int x, int y) { - return ResultWithInstance.create(x - y, microserviceProperties); + return ResultWithInstance.create(x - y, environment); } @GetMapping(path = "/download") diff --git a/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/Consumer.java b/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/Consumer.java index dc52c49cdae..43cab7bee6e 100644 --- a/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/Consumer.java +++ b/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/Consumer.java @@ -26,7 +26,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.demo.edge.model.ChannelRequestBase; import org.apache.servicecomb.demo.edge.model.DependTypeA; import org.apache.servicecomb.demo.edge.model.DependTypeB; @@ -37,6 +37,7 @@ import org.apache.servicecomb.provider.springmvc.reference.RestTemplateBuilder; import org.apache.servicecomb.registry.DiscoveryManager; import org.apache.servicecomb.registry.api.DiscoveryInstance; +import org.springframework.core.env.Environment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -65,7 +66,7 @@ public class Consumer { DiscoveryManager discoveryManager = BeanUtils.getBean(DiscoveryManager.class); - MicroserviceProperties microserviceProperties = BeanUtils.getBean(MicroserviceProperties.class); + Environment environment = BeanUtils.getBean(Environment.class); public Consumer() { request.setDeviceId("2a5cc42ff60006ac"); @@ -270,7 +271,8 @@ protected void invoke(String appendUrl, int x, int y, List r } private URIEndpointObject prepareEdge(String prefix) { - DiscoveryInstance instance = discoveryManager.findServiceInstances(microserviceProperties.getApplication(), "edge") + DiscoveryInstance instance = discoveryManager.findServiceInstances( + BootStrapProperties.readApplication(environment), "edge") .stream() .findFirst() .get(); diff --git a/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/EdgeServiceGovernanceTest.java b/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/EdgeServiceGovernanceTest.java index cfb07abe31d..3f9062a0f92 100644 --- a/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/EdgeServiceGovernanceTest.java +++ b/demo/demo-edge/consumer/src/main/java/org/apache/servicecomb/demo/edge/consumer/EdgeServiceGovernanceTest.java @@ -21,7 +21,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.demo.CategorizedTestCase; import org.apache.servicecomb.demo.TestMgr; import org.apache.servicecomb.foundation.common.net.URIEndpointObject; @@ -29,6 +29,7 @@ import org.apache.servicecomb.registry.DiscoveryManager; import org.apache.servicecomb.registry.api.DiscoveryInstance; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; @@ -40,7 +41,7 @@ public class EdgeServiceGovernanceTest implements CategorizedTestCase { String edgePrefix; @Autowired - MicroserviceProperties microserviceProperties; + Environment environment; @Autowired DiscoveryManager discoveryManager; @@ -138,7 +139,7 @@ public void run() { private URIEndpointObject prepareEdge(String prefix) { DiscoveryInstance microserviceInstance = discoveryManager.findServiceInstances( - microserviceProperties.getApplication(), "edge") + BootStrapProperties.readApplication(environment), "edge") .stream() .findFirst() .get(); diff --git a/demo/demo-edge/model/src/main/java/org/apache/servicecomb/demo/edge/model/ResultWithInstance.java b/demo/demo-edge/model/src/main/java/org/apache/servicecomb/demo/edge/model/ResultWithInstance.java index f83aa7e84e4..c225f7fee34 100644 --- a/demo/demo-edge/model/src/main/java/org/apache/servicecomb/demo/edge/model/ResultWithInstance.java +++ b/demo/demo-edge/model/src/main/java/org/apache/servicecomb/demo/edge/model/ResultWithInstance.java @@ -17,7 +17,8 @@ package org.apache.servicecomb.demo.edge.model; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; +import org.springframework.core.env.Environment; public class ResultWithInstance { private int result; @@ -28,10 +29,10 @@ public class ResultWithInstance { private String version; - public static ResultWithInstance create(int value, MicroserviceProperties microserviceProperties) { + public static ResultWithInstance create(int value, Environment environment) { ResultWithInstance result = new ResultWithInstance(); result.setResult(value); - result.setVersion(microserviceProperties.getVersion()); + result.setVersion(BootStrapProperties.readServiceVersion(environment)); return result; } diff --git a/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/CodeFirstRestTemplate.java b/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/CodeFirstRestTemplate.java index 681b5c0a00d..6f37563afb4 100644 --- a/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/CodeFirstRestTemplate.java +++ b/demo/demo-schema/src/main/java/org/apache/servicecomb/demo/CodeFirstRestTemplate.java @@ -21,8 +21,8 @@ import java.util.HashMap; import java.util.Map; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.InMemoryDynamicPropertiesSource; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.core.CoreConst; import org.apache.servicecomb.demo.compute.Person; import org.apache.servicecomb.demo.ignore.InputModelForTestIgnore; @@ -32,6 +32,7 @@ import org.apache.servicecomb.swagger.invocation.context.InvocationContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.env.Environment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -42,11 +43,11 @@ import io.vertx.core.json.JsonObject; public class CodeFirstRestTemplate { - protected MicroserviceProperties microserviceProperties; + protected Environment environment; @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public void setEnvironment(Environment environment) { + this.environment = environment; } protected void changeTransport(String microserviceName, String transport) { @@ -161,7 +162,7 @@ protected void checkStatusCode(String microserviceName, int expectStatusCode, Ht private void testCseResponse(String targetMicroserviceName, RestTemplate template, String cseUrlPrefix) { - String srcMicroserviceName = microserviceProperties.getName(); + String srcMicroserviceName = BootStrapProperties.readServiceName(environment); ResponseEntity responseEntity = template.exchange(cseUrlPrefix + "cseResponse", HttpMethod.GET, null, User.class); diff --git a/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/CodeFirstRestTemplateSpringmvc.java b/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/CodeFirstRestTemplateSpringmvc.java index fae0ad7cd80..9240dbd3845 100644 --- a/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/CodeFirstRestTemplateSpringmvc.java +++ b/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/CodeFirstRestTemplateSpringmvc.java @@ -27,13 +27,14 @@ import java.util.Map; import org.apache.commons.io.FileUtils; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.demo.CodeFirstRestTemplate; import org.apache.servicecomb.demo.TestMgr; import org.apache.servicecomb.foundation.common.part.FilePart; import org.apache.servicecomb.provider.pojo.Invoker; import org.apache.servicecomb.provider.springmvc.reference.CseHttpEntity; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; @@ -74,9 +75,9 @@ interface UploadStreamAndResource { private TestContentType testContentType = new TestContentType(); @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; - testResponse.setMicroserviceProperties(microserviceProperties); + public void setEnvironment(Environment environment) { + this.environment = environment; + testResponse.setEnvironment(environment); } @Override @@ -184,7 +185,7 @@ private void testResponseEntity(String microserviceName, RestTemplate template, CseHttpEntity> httpEntity = new CseHttpEntity<>(body); httpEntity.addContext("contextKey", "contextValue"); - String srcName = microserviceProperties.getName(); + String srcName = BootStrapProperties.readServiceName(environment); ResponseEntity responseEntity = template.exchange(cseUrlPrefix + "responseEntity", HttpMethod.POST, httpEntity, Date.class); diff --git a/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/TestResponse.java b/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/TestResponse.java index 20d8d450822..bede84dadaf 100644 --- a/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/TestResponse.java +++ b/demo/demo-springmvc/springmvc-client/src/main/java/org/apache/servicecomb/demo/springmvc/client/TestResponse.java @@ -20,7 +20,7 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.demo.TestMgr; import org.apache.servicecomb.demo.compute.GenericParam; import org.apache.servicecomb.demo.compute.Person; @@ -28,6 +28,7 @@ import org.apache.servicecomb.swagger.invocation.Response; import org.apache.servicecomb.swagger.invocation.exception.CommonExceptionData; import org.apache.servicecomb.swagger.invocation.exception.InvocationException; +import org.springframework.core.env.Environment; import org.springframework.http.ResponseEntity; import com.fasterxml.jackson.databind.exc.InvalidFormatException; @@ -35,10 +36,10 @@ public class TestResponse { private CodeFirstSpringmvcIntf intf; - private MicroserviceProperties microserviceProperties; + private Environment environment; - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public void setEnvironment(Environment environment) { + this.environment = environment; } public TestResponse() { @@ -69,7 +70,7 @@ public void runAllTransport() { } private void testCseResponse() { - String srcName = microserviceProperties.getName(); + String srcName = BootStrapProperties.readServiceName(environment); Response cseResponse = intf.cseResponse(); TestMgr.check("User [name=nameA, age=100, index=0]", cseResponse.getResult()); TestMgr.check("h1v " + srcName, cseResponse.getHeader("h1")); @@ -78,7 +79,7 @@ private void testCseResponse() { } private void testCseResponseCorrect() { - String srcName = microserviceProperties.getName(); + String srcName = BootStrapProperties.readServiceName(environment); Response cseResponse = intf.cseResponseCorrect(); TestMgr.check("User [name=nameA, age=100, index=0]", cseResponse.getResult()); TestMgr.check("h1v " + srcName, cseResponse.getHeader("h1")); @@ -89,7 +90,7 @@ private void testCseResponseCorrect() { private void testResponseEntity() { Date date = new Date(); - String srcName = microserviceProperties.getName(); + String srcName = BootStrapProperties.readServiceName(environment); ResponseEntity responseEntity = intf.responseEntity(date); TestMgr.check(date, responseEntity.getBody()); diff --git a/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloConfiguration.java b/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloConfiguration.java index ac500eafcb8..152f23962c2 100644 --- a/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloConfiguration.java +++ b/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloConfiguration.java @@ -16,19 +16,9 @@ */ package org.apache.servicecomb.config.apollo; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; @Configuration public class ApolloConfiguration { - @Bean - public ApolloDynamicPropertiesSource apolloDynamicPropertiesSource() { - return new ApolloDynamicPropertiesSource(); - } - @Bean - public ApolloConfig apolloConfig(Environment environment) { - return new ApolloConfig(environment); - } } diff --git a/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloDynamicPropertiesSource.java b/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloDynamicPropertiesSource.java index 56dd7ed390d..935877fcc4c 100644 --- a/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloDynamicPropertiesSource.java +++ b/dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/apollo/ApolloDynamicPropertiesSource.java @@ -27,12 +27,10 @@ import org.apache.servicecomb.config.DynamicPropertiesSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; -public class ApolloDynamicPropertiesSource implements DynamicPropertiesSource> { +public class ApolloDynamicPropertiesSource implements DynamicPropertiesSource { public static final String SOURCE_NAME = "apollo"; private static final Logger LOGGER = LoggerFactory.getLogger(ApolloDynamicPropertiesSource.class); @@ -42,11 +40,7 @@ public class ApolloDynamicPropertiesSource implements DynamicPropertiesSource config) { } @Override - public EnumerablePropertySource> create(Environment environment) { - init(); + public MapPropertySource create(Environment environment) { + init(environment); return new MapPropertySource(SOURCE_NAME, valueCache); } } diff --git a/dynamic-config/config-apollo/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource b/dynamic-config/config-apollo/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource new file mode 100644 index 00000000000..aa0aae8be0b --- /dev/null +++ b/dynamic-config/config-apollo/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource @@ -0,0 +1,18 @@ +# +# 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. +# + +org.apache.servicecomb.config.apollo.ApolloDynamicPropertiesSource diff --git a/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterConfiguration.java b/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterConfiguration.java index 97578fb2d3b..672a5931faf 100644 --- a/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterConfiguration.java +++ b/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterConfiguration.java @@ -17,21 +17,10 @@ package org.apache.servicecomb.config.cc; import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; public class ConfigCenterConfiguration { @Bean public ConfigCenterInformationCollector configCenterInformationCollector() { return new ConfigCenterInformationCollector(); } - - @Bean - public ConfigCenterDynamicPropertiesSource configCenterDynamicPropertiesSource() { - return new ConfigCenterDynamicPropertiesSource(); - } - - @Bean - public ConfigCenterConfig configCenterConfig(Environment environment) { - return new ConfigCenterConfig(environment); - } } diff --git a/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterDynamicPropertiesSource.java b/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterDynamicPropertiesSource.java index 22de503db5e..52f1167274c 100644 --- a/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterDynamicPropertiesSource.java +++ b/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterDynamicPropertiesSource.java @@ -27,8 +27,8 @@ import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.DynamicPropertiesSource; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.config.center.client.ConfigCenterAddressManager; import org.apache.servicecomb.config.center.client.ConfigCenterClient; import org.apache.servicecomb.config.center.client.ConfigCenterManager; @@ -46,62 +46,51 @@ import org.apache.servicecomb.http.client.common.HttpTransportFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import com.google.common.eventbus.Subscribe; -public class ConfigCenterDynamicPropertiesSource implements DynamicPropertiesSource> { +public class ConfigCenterDynamicPropertiesSource implements DynamicPropertiesSource { public static final String SOURCE_NAME = "config-center"; private static final Logger LOGGER = LoggerFactory.getLogger(ConfigCenterDynamicPropertiesSource.class); private final Map data = new ConcurrentHashMapEx<>(); - private ConfigCenterManager configCenterManager; - private ConfigConverter configConverter; - private ConfigCenterConfig configCenterConfig; - - private MicroserviceProperties microserviceProperties; - - @Autowired - public void setConfigCenterConfig(ConfigCenterConfig configCenterConfig) { - this.configCenterConfig = configCenterConfig; - } - - @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public ConfigCenterDynamicPropertiesSource() { } private void init(Environment environment) { + ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(environment); configConverter = new ConfigConverter(configCenterConfig.getFileSources()); - ConfigCenterAddressManager kieAddressManager = configKieAddressManager(); + ConfigCenterAddressManager kieAddressManager = configKieAddressManager(configCenterConfig); HttpTransport httpTransport = createHttpTransport(kieAddressManager, HttpTransportFactory.defaultRequestConfig().build(), - environment); + environment, configCenterConfig); ConfigCenterClient configCenterClient = new ConfigCenterClient(kieAddressManager, httpTransport); EventManager.register(this); - org.apache.servicecomb.config.center.client.model.ConfigCenterConfiguration configCenterConfiguration = createConfigCenterConfiguration(); + ConfigCenterConfiguration configCenterConfiguration = + createConfigCenterConfiguration(configCenterConfig); - QueryConfigurationsRequest queryConfigurationsRequest = firstPull(configCenterClient); + QueryConfigurationsRequest queryConfigurationsRequest = firstPull(configCenterConfig, configCenterClient, + environment); - configCenterManager = new ConfigCenterManager(configCenterClient, EventManager.getEventBus(), + ConfigCenterManager configCenterManager = new ConfigCenterManager(configCenterClient, EventManager.getEventBus(), configConverter, configCenterConfiguration); configCenterManager.setQueryConfigurationsRequest(queryConfigurationsRequest); configCenterManager.startConfigCenterManager(); data.putAll(configConverter.getCurrentData()); } - private QueryConfigurationsRequest firstPull(ConfigCenterClient configCenterClient) { - QueryConfigurationsRequest queryConfigurationsRequest = createQueryConfigurationsRequest(); + private QueryConfigurationsRequest firstPull(ConfigCenterConfig configCenterConfig, + ConfigCenterClient configCenterClient, Environment environment) { + QueryConfigurationsRequest queryConfigurationsRequest = createQueryConfigurationsRequest(environment); try { QueryConfigurationsResponse response = configCenterClient .queryConfigurations(queryConfigurationsRequest); @@ -125,24 +114,25 @@ public void onConfigurationChangedEvent(ConfigurationChangedEvent event) { event.getDeleted().forEach((k, v) -> data.remove(k)); } - private QueryConfigurationsRequest createQueryConfigurationsRequest() { + private QueryConfigurationsRequest createQueryConfigurationsRequest(Environment environment) { QueryConfigurationsRequest request = new QueryConfigurationsRequest(); - request.setApplication(microserviceProperties.getApplication()); - request.setServiceName(microserviceProperties.getName()); - request.setVersion(microserviceProperties.getVersion()); - request.setEnvironment(microserviceProperties.getEnvironment()); + request.setApplication(BootStrapProperties.readApplication(environment)); + request.setServiceName(BootStrapProperties.readServiceName(environment)); + request.setVersion(BootStrapProperties.readServiceVersion(environment)); + request.setEnvironment(BootStrapProperties.readServiceEnvironment(environment)); // 需要设置为 null, 并且 query 参数为 revision=null 才会返回 revision 信息。 revision = 是不行的。 request.setRevision(null); return request; } - private org.apache.servicecomb.config.center.client.model.ConfigCenterConfiguration createConfigCenterConfiguration() { + private ConfigCenterConfiguration createConfigCenterConfiguration( + ConfigCenterConfig configCenterConfig) { return new ConfigCenterConfiguration().setRefreshIntervalInMillis(configCenterConfig.getRefreshInterval()); } private HttpTransport createHttpTransport(ConfigCenterAddressManager kieAddressManager, RequestConfig requestConfig, - Environment environment) { + Environment environment, ConfigCenterConfig configCenterConfig) { List authHeaderProviders = SPIServiceUtils.getOrLoadSortedService(AuthHeaderProvider.class); if (configCenterConfig.isProxyEnable()) { @@ -179,14 +169,14 @@ private static RequestAuthHeaderProvider getRequestAuthHeaderProvider(List> create(Environment environment) { + public MapPropertySource create(Environment environment) { init(environment); return new MapPropertySource(SOURCE_NAME, data); } diff --git a/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterInformationCollector.java b/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterInformationCollector.java index e5b77412990..ab91f368013 100644 --- a/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterInformationCollector.java +++ b/dynamic-config/config-cc/src/main/java/org/apache/servicecomb/config/cc/ConfigCenterInformationCollector.java @@ -18,15 +18,17 @@ package org.apache.servicecomb.config.cc; import org.apache.servicecomb.core.bootup.BootUpInformationCollector; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.Environment; +import org.springframework.lang.NonNull; -public class ConfigCenterInformationCollector implements BootUpInformationCollector { +public class ConfigCenterInformationCollector implements BootUpInformationCollector, EnvironmentAware { private ConfigCenterConfig configCenterConfig; - @Autowired - public void setConfigCenterConfig(ConfigCenterConfig configCenterConfig) { - this.configCenterConfig = configCenterConfig; + @Override + public void setEnvironment(@NonNull Environment environment) { + this.configCenterConfig = new ConfigCenterConfig(environment); } @Override diff --git a/dynamic-config/config-cc/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource b/dynamic-config/config-cc/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource new file mode 100644 index 00000000000..94d24b08be8 --- /dev/null +++ b/dynamic-config/config-cc/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource @@ -0,0 +1,18 @@ +# +# 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. +# + +org.apache.servicecomb.config.cc.ConfigCenterDynamicPropertiesSource diff --git a/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieConfigConfiguration.java b/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieConfigConfiguration.java index 50a36237944..7b8e35bd6e4 100644 --- a/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieConfigConfiguration.java +++ b/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieConfigConfiguration.java @@ -18,21 +18,10 @@ import org.apache.servicecomb.config.kie.collect.KieClientInformationCollector; import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; public class KieConfigConfiguration { @Bean public KieClientInformationCollector kieClientInformationCollector() { return new KieClientInformationCollector(); } - - @Bean - public KieConfig kieConfig(Environment environment) { - return new KieConfig(environment); - } - - @Bean - public KieDynamicPropertiesSource kieDynamicPropertiesSource() { - return new KieDynamicPropertiesSource(); - } } diff --git a/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieDynamicPropertiesSource.java b/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieDynamicPropertiesSource.java index d18fca89dcf..b06ae113022 100644 --- a/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieDynamicPropertiesSource.java +++ b/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/KieDynamicPropertiesSource.java @@ -28,8 +28,8 @@ import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.DynamicPropertiesSource; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.config.common.ConfigConverter; import org.apache.servicecomb.config.common.ConfigurationChangedEvent; import org.apache.servicecomb.config.kie.client.KieClient; @@ -43,14 +43,12 @@ import org.apache.servicecomb.http.client.auth.RequestAuthHeaderProvider; import org.apache.servicecomb.http.client.common.HttpTransport; import org.apache.servicecomb.http.client.common.HttpTransportFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import com.google.common.eventbus.Subscribe; -public class KieDynamicPropertiesSource implements DynamicPropertiesSource> { +public class KieDynamicPropertiesSource implements DynamicPropertiesSource { public static final String SOURCE_NAME = "kie"; private final Map data = new ConcurrentHashMapEx<>(); @@ -59,23 +57,14 @@ public class KieDynamicPropertiesSource implements DynamicPropertiesSource data.remove(k)); } - private KieConfiguration createKieConfiguration() { - return new KieConfiguration().setAppName(microserviceProperties.getApplication()) + private KieConfiguration createKieConfiguration(KieConfig kieConfig, Environment environment) { + return new KieConfiguration() + .setAppName(BootStrapProperties.readApplication(environment)) + .setServiceName(BootStrapProperties.readServiceName(environment)) + .setEnvironment(BootStrapProperties.readServiceEnvironment(environment)) + .setVersion(BootStrapProperties.readServiceVersion(environment)) .setFirstPullRequired(kieConfig.firstPullRequired()) .setCustomLabel(kieConfig.getCustomLabel()) .setCustomLabelValue(kieConfig.getCustomLabelValue()) @@ -111,15 +104,13 @@ private KieConfiguration createKieConfiguration() { .setEnableLongPolling(kieConfig.enableLongPolling()) .setEnableServiceConfig(kieConfig.enableServiceConfig()) .setEnableVersionConfig(kieConfig.enableVersionConfig()) - .setEnvironment(microserviceProperties.getEnvironment()) - .setVersion(microserviceProperties.getVersion()) .setPollingWaitInSeconds(kieConfig.getPollingWaitTime()) .setProject(kieConfig.getDomainName()) - .setRefreshIntervalInMillis(kieConfig.getRefreshInterval()) - .setServiceName(microserviceProperties.getName()); + .setRefreshIntervalInMillis(kieConfig.getRefreshInterval()); } - private HttpTransport createHttpTransport(KieAddressManager kieAddressManager, RequestConfig requestConfig, + private HttpTransport createHttpTransport(KieAddressManager kieAddressManager, + RequestConfig requestConfig, KieConfig kieConfig, Environment environment) { List authHeaderProviders = SPIServiceUtils.getOrLoadSortedService(AuthHeaderProvider.class); @@ -157,13 +148,13 @@ private static RequestAuthHeaderProvider getRequestAuthHeaderProvider(List> create(Environment environment) { + public MapPropertySource create(Environment environment) { init(environment); return new MapPropertySource(SOURCE_NAME, data); } diff --git a/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/collect/KieClientInformationCollector.java b/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/collect/KieClientInformationCollector.java index 135f0319a23..d689aaec2e1 100644 --- a/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/collect/KieClientInformationCollector.java +++ b/dynamic-config/config-kie/src/main/java/org/apache/servicecomb/config/kie/collect/KieClientInformationCollector.java @@ -19,15 +19,16 @@ import org.apache.servicecomb.config.kie.KieConfig; import org.apache.servicecomb.core.bootup.BootUpInformationCollector; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.Environment; +import org.springframework.lang.NonNull; - -public class KieClientInformationCollector implements BootUpInformationCollector { +public class KieClientInformationCollector implements BootUpInformationCollector, EnvironmentAware { private KieConfig kieConfig; - @Autowired - public void setKieConfig(KieConfig kieConfig) { - this.kieConfig = kieConfig; + @Override + public void setEnvironment(@NonNull Environment environment) { + this.kieConfig = new KieConfig(environment); } @Override diff --git a/dynamic-config/config-kie/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource b/dynamic-config/config-kie/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource new file mode 100644 index 00000000000..1ff1d0d0bb4 --- /dev/null +++ b/dynamic-config/config-kie/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource @@ -0,0 +1,18 @@ +# +# 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. +# + +org.apache.servicecomb.config.kie.KieDynamicPropertiesSource diff --git a/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosClient.java b/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosClient.java index 7d79c52b728..2f774571a77 100644 --- a/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosClient.java +++ b/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosClient.java @@ -32,7 +32,7 @@ import org.apache.servicecomb.config.parser.Parser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; @@ -46,15 +46,11 @@ public class NacosClient { private final UpdateHandler updateHandler; - private NacosConfig nacosConfig; + private final NacosConfig nacosConfig; - public NacosClient(UpdateHandler updateHandler) { + public NacosClient(UpdateHandler updateHandler, Environment environment) { this.updateHandler = updateHandler; - } - - @Autowired - public void setNacosConfig(NacosConfig nacosConfig) { - this.nacosConfig = nacosConfig; + this.nacosConfig = new NacosConfig(environment); } public void refreshNacosConfig() { diff --git a/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosConfigConfiguration.java b/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosConfigConfiguration.java index bad19c3dc41..969d621b1fa 100644 --- a/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosConfigConfiguration.java +++ b/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosConfigConfiguration.java @@ -16,17 +16,6 @@ */ package org.apache.servicecomb.config.nacos; -import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; - public class NacosConfigConfiguration { - @Bean - public NacosConfig nacosConfig(Environment environment) { - return new NacosConfig(environment); - } - @Bean - public NacosDynamicPropertiesSource nacosDynamicPropertiesSource() { - return new NacosDynamicPropertiesSource(); - } } diff --git a/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosDynamicPropertiesSource.java b/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosDynamicPropertiesSource.java index bb6d327807d..1ee1750f9f1 100644 --- a/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosDynamicPropertiesSource.java +++ b/dynamic-config/config-nacos/src/main/java/org/apache/servicecomb/config/nacos/NacosDynamicPropertiesSource.java @@ -27,13 +27,12 @@ import org.apache.servicecomb.config.DynamicPropertiesSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; import com.google.common.annotations.VisibleForTesting; -public class NacosDynamicPropertiesSource implements DynamicPropertiesSource> { +public class NacosDynamicPropertiesSource implements DynamicPropertiesSource { public static final String SOURCE_NAME = "kie"; private static final Logger LOGGER = LoggerFactory.getLogger(NacosDynamicPropertiesSource.class); @@ -52,7 +51,7 @@ UpdateHandler getUpdateHandler() { private void init(Environment environment) { - NacosClient nacosClient = new NacosClient(updateHandler); + NacosClient nacosClient = new NacosClient(updateHandler, environment); nacosClient.refreshNacosConfig(); } @@ -77,7 +76,7 @@ public void handle(ConfigurationAction action, Map config) { } @Override - public EnumerablePropertySource> create(Environment environment) { + public MapPropertySource create(Environment environment) { init(environment); return new MapPropertySource(SOURCE_NAME, valueCache); } diff --git a/dynamic-config/config-nacos/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource b/dynamic-config/config-nacos/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource new file mode 100644 index 00000000000..f7b7e102457 --- /dev/null +++ b/dynamic-config/config-nacos/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource @@ -0,0 +1,18 @@ +# +# 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. +# + +org.apache.servicecomb.config.nacos.NacosDynamicPropertiesSource diff --git a/dynamic-config/config-nacos/src/test/java/org/apache/servicecomb/config/nacos/NacosClientTest.java b/dynamic-config/config-nacos/src/test/java/org/apache/servicecomb/config/nacos/NacosClientTest.java index 119bc73caa9..718c45d2288 100644 --- a/dynamic-config/config-nacos/src/test/java/org/apache/servicecomb/config/nacos/NacosClientTest.java +++ b/dynamic-config/config-nacos/src/test/java/org/apache/servicecomb/config/nacos/NacosClientTest.java @@ -24,6 +24,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.core.env.Environment; public class NacosClientTest { @@ -33,12 +34,13 @@ public void testCompareChangedConfig() { Map before = new HashMap<>(); Map after = new HashMap<>(); + Environment environment = Mockito.mock(Environment.class); + Mockito.when(environment.getProperty(NacosConfig.CONTENT_TYPE, "yaml")).thenReturn("yaml"); NacosDynamicPropertiesSource impl = new NacosDynamicPropertiesSource(); UpdateHandler updateHandler = impl.new UpdateHandler(); - NacosClient nacosClient = new NacosClient(updateHandler); + NacosClient nacosClient = new NacosClient(updateHandler, environment); NacosConfig nacosConfig = Mockito.mock(NacosConfig.class); Mockito.when(nacosConfig.getContentType()).thenReturn("yaml"); - nacosClient.setNacosConfig(nacosConfig); NacosClient.ConfigRefresh cr = nacosClient.new ConfigRefresh(); diff --git a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/CommonHttpEdgeDispatcher.java b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/CommonHttpEdgeDispatcher.java index baed88dd427..d771fa80a3b 100644 --- a/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/CommonHttpEdgeDispatcher.java +++ b/edge/edge-core/src/main/java/org/apache/servicecomb/edge/core/CommonHttpEdgeDispatcher.java @@ -20,8 +20,8 @@ import java.util.HashMap; import java.util.Map; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.ConfigurationChangedEvent; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.core.Invocation; import org.apache.servicecomb.foundation.common.LegacyPropertyFactory; import org.apache.servicecomb.foundation.common.cache.VersionedCache; @@ -98,8 +98,8 @@ protected DiscoveryTree getDiscoveryTree() { } // Maybe future change to beans - protected MicroserviceProperties getMicroserviceProperties() { - return BeanUtils.getBean(MicroserviceProperties.class); + protected Environment getEnvironment() { + return BeanUtils.getBean(Environment.class); } // Maybe future change to beans @@ -223,7 +223,7 @@ protected LoadBalancer getOrCreateLoadBalancer(Invocation invocation, String mic DiscoveryContext context = new DiscoveryContext(); context.setInputParameters(invocation); VersionedCache serversVersionedCache = getDiscoveryTree().discovery(context, - getMicroserviceProperties().getApplication(), + BootStrapProperties.readApplication(environment), microserviceName); invocation.addLocalContext(LoadBalanceFilter.CONTEXT_KEY_SERVER_LIST, serversVersionedCache.data()); return loadBalancerMap diff --git a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/BootStrapProperties.java b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/BootStrapProperties.java index 1023bdb38bc..046b326b8b2 100644 --- a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/BootStrapProperties.java +++ b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/BootStrapProperties.java @@ -28,6 +28,18 @@ /** * This class holds configurations that need to be configured * through property files or environment variables. + * + * These properties are core model for java chassis, e.g. + *
+ *   servicecomb:
+ *     service:
+ *       application:
+ *       name:
+ *       version:
+ *       environment:
+ *       properties:
+ * 
+ * */ public class BootStrapProperties { // start of : service definition keys @@ -40,6 +52,8 @@ public class BootStrapProperties { public static final String OLD_CONFIG_SERVICE_ROLE = "service_description.role"; + public static final String OLD_CONFIG_SERVICE_ALIAS = "service_description.alias"; + public static final String OLD_CONFIG_SERVICE_DESCRIPTION = "service_description.description"; public static final String OLD_CONFIG_SERVICE_ENVIRONMENT = "service_description.environment"; @@ -64,6 +78,8 @@ public class BootStrapProperties { public static final String CONFIG_SERVICE_ROLE = "servicecomb.service.role"; + public static final String CONFIG_SERVICE_ALIAS = "servicecomb.service.alias"; + public static final String CONFIG_SERVICE_DESCRIPTION = "servicecomb.service.description"; public static final String CONFIG_SERVICE_ENVIRONMENT = "servicecomb.service.environment"; @@ -113,6 +129,10 @@ public static String readServiceRole(Environment environment) { return readStringValue(environment, CONFIG_SERVICE_ROLE, OLD_CONFIG_SERVICE_ROLE, DEFAULT_MICROSERVICE_ROLE); } + public static String readServiceAlias(Environment environment) { + return readStringValue(environment, CONFIG_SERVICE_ALIAS, OLD_CONFIG_SERVICE_ALIAS, null); + } + public static String readServiceDescription(Environment environment) { String[] descriptionArray = environment.getProperty(CONFIG_SERVICE_DESCRIPTION, String[].class); if (null == descriptionArray || descriptionArray.length < 1) { diff --git a/core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringBootInitializer.java b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigEnvironmentPostProcessor.java similarity index 80% rename from core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringBootInitializer.java rename to foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigEnvironmentPostProcessor.java index 3e401a42dd9..0edb84541bc 100644 --- a/core/src/main/java/org/apache/servicecomb/core/ConfigurationSpringBootInitializer.java +++ b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/ConfigEnvironmentPostProcessor.java @@ -14,18 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.servicecomb.core; +package org.apache.servicecomb.config; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.apache.servicecomb.config.ConfigMapping; -import org.apache.servicecomb.config.YAMLUtil; import org.apache.servicecomb.config.file.MicroserviceConfigLoader; import org.apache.servicecomb.foundation.bootstrap.BootStrapService; import org.apache.servicecomb.foundation.common.utils.SPIServiceUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.context.annotation.Conditional; @@ -36,20 +36,20 @@ import org.springframework.core.env.MutablePropertySources; /** - * Add microservice.yaml to Environment earlier
- * to affect {@link Conditional}
+ * Initialize configuration. */ -public class ConfigurationSpringBootInitializer implements EnvironmentPostProcessor { +public class ConfigEnvironmentPostProcessor implements EnvironmentPostProcessor { + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigEnvironmentPostProcessor.class); + public static final String MICROSERVICE_PROPERTY_SOURCE_NAME = "microservice.yaml"; public static final String MAPPING_PROPERTY_SOURCE_NAME = "mapping.yaml"; - private final List bootStrapServices = SPIServiceUtils.getSortedService(BootStrapService.class); - @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { addMicroserviceDefinitions(environment); startupBootStrapService(environment); + addDynamicConfigurationToSpring(environment); } public static void addMicroserviceDefinitions(Environment environment) { @@ -58,7 +58,9 @@ public static void addMicroserviceDefinitions(Environment environment) { } private void startupBootStrapService(Environment environment) { - bootStrapServices.forEach(bootStrapService -> bootStrapService.startup(environment)); + for (BootStrapService bootStrapService : SPIServiceUtils.getSortedService(BootStrapService.class)) { + bootStrapService.startup(environment); + } } /** @@ -126,4 +128,19 @@ private static void addMappingToSpring(Environment environment) { Map mappings = ConfigMapping.getConvertedMap(environment); propertySources.addFirst(new MapPropertySource(MAPPING_PROPERTY_SOURCE_NAME, mappings)); } + + private void addDynamicConfigurationToSpring(Environment environment) { + if (!(environment instanceof ConfigurableEnvironment)) { + return; + } + try { + for (DynamicPropertiesSource dynamicPropertiesSource : + SPIServiceUtils.getOrLoadSortedService(DynamicPropertiesSource.class)) { + ((ConfigurableEnvironment) environment).getPropertySources() + .addFirst(dynamicPropertiesSource.create(environment)); + } + } catch (Exception e) { + LOGGER.warn("set up dynamic property source to spring failed.", e); + } + } } diff --git a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/DynamicPropertiesSource.java b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/DynamicPropertiesSource.java index 8833d26af13..87af7f66f28 100644 --- a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/DynamicPropertiesSource.java +++ b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/DynamicPropertiesSource.java @@ -17,9 +17,12 @@ package org.apache.servicecomb.config; import org.springframework.core.Ordered; -import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; +import org.springframework.core.env.MapPropertySource; -public interface DynamicPropertiesSource extends Ordered { - EnumerablePropertySource create(Environment environment); +/** + * SPI to add new DynamicPropertiesSource. + */ +public interface DynamicPropertiesSource extends Ordered { + MapPropertySource create(Environment environment); } diff --git a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/FoundationConfigConfiguration.java b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/FoundationConfigConfiguration.java index a89cd16a47b..9cb7c231a25 100644 --- a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/FoundationConfigConfiguration.java +++ b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/FoundationConfigConfiguration.java @@ -44,11 +44,6 @@ public PriorityPropertyFactory priorityPropertyFactory(Environment environment) return new PriorityPropertyFactory(environment); } - @Bean - public LastPropertyPlaceholderConfigurer lastPropertyPlaceholderConfigurer() { - return new LastPropertyPlaceholderConfigurer(); - } - @Bean public DynamicPropertiesImpl dynamicProperties(Environment environment) { return new DynamicPropertiesImpl(environment); @@ -59,12 +54,6 @@ public ConfigObjectFactory configObjectFactory(PriorityPropertyFactory propertyF return new ConfigObjectFactory(propertyFactory); } - @Bean - @ConfigurationProperties(prefix = MicroserviceProperties.PREFIX) - public MicroserviceProperties microserviceProperties() { - return new MicroserviceProperties(); - } - @Bean @ConfigurationProperties(prefix = DataCenterProperties.PREFIX) public DataCenterProperties dataCenterProperties() { diff --git a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/InMemoryDynamicPropertiesSource.java b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/InMemoryDynamicPropertiesSource.java index e9a450f92e4..8ce73d7274b 100644 --- a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/InMemoryDynamicPropertiesSource.java +++ b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/InMemoryDynamicPropertiesSource.java @@ -20,20 +20,19 @@ import java.util.Map; import org.apache.servicecomb.foundation.common.event.EventManager; -import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.MapPropertySource; /** * This DynamicPropertiesSource is created for easier system tests. */ -public class InMemoryDynamicPropertiesSource implements DynamicPropertiesSource> { +public class InMemoryDynamicPropertiesSource implements DynamicPropertiesSource { public static final String SOURCE_NAME = "in-memory"; private static final Map DYNAMIC = new HashMap<>(); @Override - public EnumerablePropertySource> create(Environment environment) { + public MapPropertySource create(Environment environment) { return new MapPropertySource(SOURCE_NAME, DYNAMIC); } diff --git a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/LastPropertyPlaceholderConfigurer.java b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/LastPropertyPlaceholderConfigurer.java deleted file mode 100644 index ec5054bb716..00000000000 --- a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/LastPropertyPlaceholderConfigurer.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.apache.servicecomb.config; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.Ordered; - -// do not implements PriorityOrdered, must be Ordered -// because this bean must run after PropertyPlaceholderConfigurer -// this class's purpose: when asked to resolve placeholder, then throw exception directly -public class LastPropertyPlaceholderConfigurer implements BeanFactoryPostProcessor, Ordered { - @Override - public int getOrder() { - return Ordered.LOWEST_PRECEDENCE; - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - new PropertySourcesPlaceholderConfigurer().postProcessBeanFactory(beanFactory); - } -} diff --git a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/MicroserviceProperties.java b/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/MicroserviceProperties.java deleted file mode 100644 index a0baab1f83e..00000000000 --- a/foundations/foundation-config/src/main/java/org/apache/servicecomb/config/MicroserviceProperties.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * 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.apache.servicecomb.config; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -public class MicroserviceProperties { - public static final String PREFIX = "servicecomb.service"; - - private String environment; - - private String application; - - private String name; - - private String alias; - - private String version; - - private String description; - - private Map properties = new HashMap<>(); - - public String getEnvironment() { - return environment; - } - - public void setEnvironment(String environment) { - this.environment = environment; - } - - public String getApplication() { - if (StringUtils.isEmpty(application)) { - throw new IllegalStateException( - "Application Name is required in configuration. NOTICE: since 3.0.0, only support " - + PREFIX + ".application to configure microservice application."); - } - return application; - } - - public void setApplication(String application) { - this.application = application; - } - - public String getName() { - if (StringUtils.isEmpty(name)) { - throw new IllegalStateException( - "Service Name is required in configuration. NOTICE: since 3.0.0, only support " - + PREFIX + ".name to configure microservice name."); - } - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - - public String getVersion() { - if (StringUtils.isEmpty(version)) { - throw new IllegalStateException( - "Service version is required in configuration. NOTICE: since 3.0.0, only support " - + PREFIX + ".version to configure microservice version."); - } - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } -} diff --git a/foundations/foundation-config/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource b/foundations/foundation-config/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource new file mode 100644 index 00000000000..1f148e651eb --- /dev/null +++ b/foundations/foundation-config/src/main/resources/META-INF/services/org.apache.servicecomb.config.DynamicPropertiesSource @@ -0,0 +1,18 @@ +# +# 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. +# + +org.apache.servicecomb.config.InMemoryDynamicPropertiesSource diff --git a/core/src/main/resources/META-INF/spring.factories b/foundations/foundation-config/src/main/resources/META-INF/spring.factories similarity index 92% rename from core/src/main/resources/META-INF/spring.factories rename to foundations/foundation-config/src/main/resources/META-INF/spring.factories index 9c04cb2cefe..1654b618370 100644 --- a/core/src/main/resources/META-INF/spring.factories +++ b/foundations/foundation-config/src/main/resources/META-INF/spring.factories @@ -15,4 +15,4 @@ # limitations under the License. # org.springframework.boot.env.EnvironmentPostProcessor=\ - org.apache.servicecomb.core.ConfigurationSpringBootInitializer + org.apache.servicecomb.config.ConfigEnvironmentPostProcessor diff --git a/foundations/foundation-config/src/test/java/org/apache/servicecomb/config/TestLastPropertyPlaceholderConfigurer.java b/foundations/foundation-config/src/test/java/org/apache/servicecomb/config/TestLastPropertyPlaceholderConfigurer.java deleted file mode 100644 index fa6f3e2fe4e..00000000000 --- a/foundations/foundation-config/src/test/java/org/apache/servicecomb/config/TestLastPropertyPlaceholderConfigurer.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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.apache.servicecomb.config; - -import java.io.IOException; -import java.util.Properties; - -import org.junit.Test; -import org.junit.jupiter.api.Assertions; -import org.springframework.context.EmbeddedValueResolverAware; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.stereotype.Component; -import org.springframework.util.StringValueResolver; - -public class TestLastPropertyPlaceholderConfigurer { - @Component - static class Bean extends PropertySourcesPlaceholderConfigurer implements EmbeddedValueResolverAware { - StringValueResolver resolver; - - public Bean() { - setIgnoreUnresolvablePlaceholders(true); - } - - @Override - public void setEmbeddedValueResolver(StringValueResolver resolver) { - this.resolver = resolver; - } - - @Override - protected Properties mergeProperties() throws IOException { - Properties properties = super.mergeProperties(); - properties.put("a", "aValue"); - return properties; - } - } - - @Test - public void test() { - AnnotationConfigApplicationContext context = - new AnnotationConfigApplicationContext(this.getClass().getPackage().getName()); - Bean bean = context.getBean(Bean.class); - - Assertions.assertEquals("aValue", bean.resolver.resolveStringValue("${a}")); - try { - bean.resolver.resolveStringValue("${b}"); - Assertions.fail("must throw exception"); - } catch (IllegalArgumentException e) { - Assertions.assertEquals("Could not resolve placeholder 'b' in value \"${b}\"", e.getMessage()); - } - - context.close(); - } -} diff --git a/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilter.java b/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilter.java index 9ee50d5b420..7dbe070237d 100644 --- a/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilter.java +++ b/handlers/handler-loadbalance/src/main/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilter.java @@ -25,7 +25,7 @@ import java.util.Optional; import org.apache.commons.lang3.StringUtils; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.Invocation; import org.apache.servicecomb.registry.discovery.AbstractDiscoveryFilter; import org.apache.servicecomb.registry.discovery.DiscoveryContext; @@ -34,6 +34,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import jakarta.validation.constraints.NotNull; @@ -48,11 +49,11 @@ public class PriorityInstancePropertyDiscoveryFilter extends AbstractDiscoveryFi private String propertyKey; - private MicroserviceProperties microserviceProperties; + private Environment environment; @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public void setEnvironment(Environment environment) { + this.environment = environment; } @Override @@ -85,7 +86,7 @@ protected String findChildName(DiscoveryContext context, DiscoveryTreeNode paren String initPropertyValue = invocation.getContext() .computeIfAbsent("x-" + propertyKey, key -> new PriorityInstanceProperty(propertyKey, - microserviceProperties.getProperties().get(propertyKey)) + BootStrapProperties.readServiceProperties(environment).get(propertyKey)) .getPropertyValue()); PriorityInstanceProperty currentProperty = context.getContextParameter(propertyKey); diff --git a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter.java b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter.java index e7a0c06870f..dc61706f568 100644 --- a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter.java +++ b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/TestLoadBalanceFilter.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.Invocation; import org.apache.servicecomb.core.SCBEngine; import org.apache.servicecomb.core.Transport; @@ -75,7 +76,12 @@ public class TestLoadBalanceFilter { public void setUp() { Environment environment = Mockito.mock(Environment.class); scbEngine = SCBBootstrap.createSCBEngineForTest(environment); - scbEngine.setEnvironment(environment); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)) + .thenReturn(BootStrapProperties.DEFAULT_APPLICATION); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_NAME)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_NAME); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_ENVIRONMENT)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_ENVIRONMENT); Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); Mockito.when(environment.getProperty("servicecomb.loadbalance.userDefinedEndpoint.enabled", diff --git a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilterTest.java b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilterTest.java index e5612695475..23f7c92f636 100644 --- a/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilterTest.java +++ b/handlers/handler-loadbalance/src/test/java/org/apache/servicecomb/loadbalance/filter/PriorityInstancePropertyDiscoveryFilterTest.java @@ -27,9 +27,7 @@ import java.util.Set; import java.util.stream.Collectors; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.core.Invocation; -import org.apache.servicecomb.registry.RegistrationManager; import org.apache.servicecomb.registry.api.DiscoveryInstance; import org.apache.servicecomb.registry.discovery.DiscoveryContext; import org.apache.servicecomb.registry.discovery.DiscoveryTreeNode; @@ -38,12 +36,12 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import org.springframework.core.env.Environment; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.MutablePropertySources; import com.google.common.collect.Sets; -import mockit.Injectable; - /** * Test for PriorityInstancePropertyDiscoveryFilter */ @@ -55,26 +53,28 @@ public class PriorityInstancePropertyDiscoveryFilterTest { private List instances; - private MicroserviceProperties self; - - @Injectable - RegistrationManager registrationManager; - - RegistrationManager original; - StatefulDiscoveryInstance instance1; - Environment environment = Mockito.mock(Environment.class); + ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class); + + EnumerablePropertySource propertySource; @Before public void setUp() { + propertySource = Mockito.mock(EnumerablePropertySource.class); + MutablePropertySources mutablePropertySources = new MutablePropertySources(); + mutablePropertySources.addLast(propertySource); + Mockito.when(environment.getPropertySources()).thenReturn(mutablePropertySources); + Mockito.when(propertySource.getPropertyNames()).thenReturn(new String[] { + "servicecomb.service.properties." + PROPERTY_KEY + }); + filter = new PriorityInstancePropertyDiscoveryFilter(); filter.setEnvironment(environment); Mockito.when(environment.getProperty("servicecomb.loadbalance.filter.priorityInstanceProperty.key", String.class, "environment")).thenReturn("environment"); instances = new ArrayList<>(); - self = new MicroserviceProperties(); - filter.setMicroserviceProperties(self); + filter.setEnvironment(environment); DiscoveryInstance discoveryInstance1 = Mockito.mock(DiscoveryInstance.class); instance1 = new StatefulDiscoveryInstance(discoveryInstance1); Mockito.when(discoveryInstance1.getInstanceId()).thenReturn("instance.empty"); @@ -135,10 +135,11 @@ public void testGetFilteredListOfServers() { private void executeTest(String selfProperty, Set expectedMatchedKeys) { + Mockito.when(environment.getProperty("servicecomb.service.properties." + PROPERTY_KEY)).thenReturn(selfProperty); + Invocation invocation = new Invocation(); DiscoveryContext discoveryContext = new DiscoveryContext(); discoveryContext.setInputParameters(invocation); - self.getProperties().put(PROPERTY_KEY, selfProperty); DiscoveryTreeNode parent = new DiscoveryTreeNode(); parent.name("parent"); diff --git a/handlers/handler-publickey-auth/src/main/java/org/apache/servicecomb/authentication/consumer/ConsumerTokenManager.java b/handlers/handler-publickey-auth/src/main/java/org/apache/servicecomb/authentication/consumer/ConsumerTokenManager.java index 7e5c40794f5..8da889abc02 100644 --- a/handlers/handler-publickey-auth/src/main/java/org/apache/servicecomb/authentication/consumer/ConsumerTokenManager.java +++ b/handlers/handler-publickey-auth/src/main/java/org/apache/servicecomb/authentication/consumer/ConsumerTokenManager.java @@ -19,12 +19,13 @@ import java.security.PrivateKey; import org.apache.servicecomb.authentication.RSAAuthenticationToken; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.foundation.common.utils.KeyPairUtils; import org.apache.servicecomb.foundation.token.Keypair4Auth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; public class ConsumerTokenManager { @@ -34,11 +35,11 @@ public class ConsumerTokenManager { private RSAAuthenticationToken token; - private MicroserviceProperties microserviceProperties; + private Environment environment; @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; + public void setEnvironment(Environment environment) { + this.environment = environment; } public String getToken() { @@ -55,8 +56,8 @@ public String getToken() { public String createToken() { PrivateKey privateKey = Keypair4Auth.INSTANCE.getPrivateKey(); - String instanceId = microserviceProperties.getName(); - String serviceId = microserviceProperties.getApplication(); + String instanceId = BootStrapProperties.readServiceName(environment); + String serviceId = BootStrapProperties.readApplication(environment); if (instanceId == null || serviceId == null) { LOGGER.error("service not ready when create token."); diff --git a/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/TestAuthenticationBootListener.java b/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/TestAuthenticationBootListener.java index ca222f5b623..28cb8d48d2d 100644 --- a/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/TestAuthenticationBootListener.java +++ b/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/TestAuthenticationBootListener.java @@ -22,6 +22,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.core.BootListener; import org.apache.servicecomb.core.BootListener.BootEvent; import org.apache.servicecomb.core.SCBEngine; @@ -32,7 +33,6 @@ import org.apache.servicecomb.registry.definition.DefinitionConst; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -41,10 +41,11 @@ public class TestAuthenticationBootListener { private SCBEngine engine; - static Environment environment = Mockito.mock(Environment.class); + private Environment environment; - @BeforeAll - public static void setUpClass() { + @BeforeEach + public void setUp() { + environment = Mockito.mock(Environment.class); LegacyPropertyFactory.setEnvironment(environment); Mockito.when(environment.getProperty("servicecomb.publicKey.accessControl.keyGeneratorAlgorithm", "RSA")) .thenReturn("RSA"); @@ -54,10 +55,13 @@ public static void setUpClass() { .thenReturn(2048); Mockito.when(environment.getProperty(CFG_KEY_TURN_DOWN_STATUS_WAIT_SEC, long.class, DEFAULT_TURN_DOWN_STATUS_WAIT_SEC)).thenReturn(DEFAULT_TURN_DOWN_STATUS_WAIT_SEC); - } + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)) + .thenReturn(BootStrapProperties.DEFAULT_APPLICATION); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_NAME)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_NAME); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_ENVIRONMENT)) + .thenReturn(BootStrapProperties.DEFAULT_MICROSERVICE_ENVIRONMENT); - @BeforeEach - public void setUp() { engine = SCBBootstrap.createSCBEngineForTest(environment); engine.run(); } diff --git a/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/provider/TestProviderTokenManager.java b/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/provider/TestProviderTokenManager.java index 5c9777be48e..801f91e697d 100644 --- a/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/provider/TestProviderTokenManager.java +++ b/handlers/handler-publickey-auth/src/test/java/org/apache/servicecomb/authentication/provider/TestProviderTokenManager.java @@ -25,7 +25,7 @@ import org.apache.servicecomb.authentication.RSAAuthenticationToken; import org.apache.servicecomb.authentication.consumer.ConsumerTokenManager; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.foundation.common.LegacyPropertyFactory; import org.apache.servicecomb.foundation.common.utils.KeyPairEntry; import org.apache.servicecomb.foundation.common.utils.KeyPairUtils; @@ -134,10 +134,10 @@ public void testTokenFromValidatePool() { String instanceId = "test"; ConsumerTokenManager consumerTokenManager = new ConsumerTokenManager(); - MicroserviceProperties microserviceProperties = Mockito.mock(MicroserviceProperties.class); - Mockito.when(microserviceProperties.getName()).thenReturn("test"); - Mockito.when(microserviceProperties.getApplication()).thenReturn("test"); - consumerTokenManager.setMicroserviceProperties(microserviceProperties); + ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_NAME)).thenReturn("test"); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)).thenReturn("test"); + consumerTokenManager.setEnvironment(environment); DiscoveryInstance microserviceInstance = Mockito.mock(DiscoveryInstance.class); Mockito.when(microserviceInstance.getInstanceId()).thenReturn(instanceId); Map properties = new HashMap<>(); @@ -151,7 +151,7 @@ public void testTokenFromValidatePool() { // use cache token Assertions.assertEquals(token, consumerTokenManager.getToken()); ProviderTokenManager rsaProviderTokenManager = new ProviderTokenManager(); - ConfigurableEnvironment environment = Mockito.mock(ConfigurableEnvironment.class); + MutablePropertySources mutablePropertySources = new MutablePropertySources(); Mockito.when(environment.getPropertySources()).thenReturn(mutablePropertySources); rsaProviderTokenManager.setAccessController(new AccessController(environment)); diff --git a/metrics/metrics-integration/metrics-prometheus/src/main/java/org/apache/servicecomb/metrics/prometheus/PrometheusPublisher.java b/metrics/metrics-integration/metrics-prometheus/src/main/java/org/apache/servicecomb/metrics/prometheus/PrometheusPublisher.java index 8ebc1acfac2..12ae5041d1f 100644 --- a/metrics/metrics-integration/metrics-prometheus/src/main/java/org/apache/servicecomb/metrics/prometheus/PrometheusPublisher.java +++ b/metrics/metrics-integration/metrics-prometheus/src/main/java/org/apache/servicecomb/metrics/prometheus/PrometheusPublisher.java @@ -21,7 +21,7 @@ import java.util.ArrayList; import java.util.List; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.foundation.common.exceptions.ServiceCombException; import org.apache.servicecomb.foundation.metrics.MetricsBootstrapConfig; import org.apache.servicecomb.foundation.metrics.MetricsInitializer; @@ -51,15 +51,8 @@ public class PrometheusPublisher extends Collector implements Collector.Describa private GlobalRegistry globalRegistry; - private MicroserviceProperties microserviceProperties; - private Environment environment; - @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; - } - @Autowired public void setEnvironment(Environment environment) { this.environment = environment; @@ -119,7 +112,7 @@ protected Sample convertMeasurementToSample(Measurement measurement) { List labelValues = new ArrayList<>(); labelNames.add("appId"); - labelValues.add(microserviceProperties.getApplication()); + labelValues.add(BootStrapProperties.readApplication(environment)); for (Tag tag : measurement.id().tags()) { labelNames.add(tag.key()); diff --git a/metrics/metrics-integration/metrics-prometheus/src/test/java/org/apache/servicecomb/metrics/prometheus/TestPrometheusPublisher.java b/metrics/metrics-integration/metrics-prometheus/src/test/java/org/apache/servicecomb/metrics/prometheus/TestPrometheusPublisher.java index a8549059fc9..167a66b4082 100644 --- a/metrics/metrics-integration/metrics-prometheus/src/test/java/org/apache/servicecomb/metrics/prometheus/TestPrometheusPublisher.java +++ b/metrics/metrics-integration/metrics-prometheus/src/test/java/org/apache/servicecomb/metrics/prometheus/TestPrometheusPublisher.java @@ -30,7 +30,7 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.reflect.FieldUtils; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.foundation.common.exceptions.ServiceCombException; import org.apache.servicecomb.foundation.metrics.MetricsBootstrapConfig; import org.apache.servicecomb.foundation.metrics.registry.GlobalRegistry; @@ -99,11 +99,10 @@ public void testBadPublishAddress_TooLargePort() { @Test public void collect() throws IllegalAccessException, IOException { - MicroserviceProperties microserviceProperties = Mockito.mock(MicroserviceProperties.class); - Mockito.when(microserviceProperties.getApplication()).thenReturn("testAppId"); + Mockito.when(environment.getProperty(BootStrapProperties.CONFIG_SERVICE_APPLICATION)).thenReturn("testAppId"); Mockito.when(environment.getProperty(METRICS_PROMETHEUS_ADDRESS, String.class, "0.0.0.0:9696")) .thenReturn("localhost:0"); - publisher.setMicroserviceProperties(microserviceProperties); + publisher.setEnvironment(environment); publisher.init(globalRegistry, null, new MetricsBootstrapConfig(environment)); Registry registry = new DefaultRegistry(new ManualClock()); diff --git a/service-registry/registry-lightweight/src/main/java/org/apache/servicecomb/registry/lightweight/LightWeightRegistryConfiguration.java b/service-registry/registry-lightweight/src/main/java/org/apache/servicecomb/registry/lightweight/LightWeightRegistryConfiguration.java index 0a78a3d2fe4..78ab582e135 100644 --- a/service-registry/registry-lightweight/src/main/java/org/apache/servicecomb/registry/lightweight/LightWeightRegistryConfiguration.java +++ b/service-registry/registry-lightweight/src/main/java/org/apache/servicecomb/registry/lightweight/LightWeightRegistryConfiguration.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.List; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.localregistry.RegistryBean; import org.apache.servicecomb.localregistry.RegistryBean.Instance; import org.apache.servicecomb.localregistry.RegistryBean.Instances; @@ -27,6 +27,7 @@ import org.apache.servicecomb.registry.lightweight.store.Store; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import com.google.common.eventbus.EventBus; @@ -62,8 +63,8 @@ public DiscoveryEndpoint zeroConfigDiscoveryEndpoint(Self self) { } @Bean - public RegistryBean zeroConfigDiscoveryServer(MicroserviceProperties microserviceProperties) { - return new RegistryBean().setAppId(microserviceProperties.getApplication()) + public RegistryBean zeroConfigDiscoveryServer(Environment environment) { + return new RegistryBean().setAppId(BootStrapProperties.readApplication(environment)) .setServiceName(ZERO_CONFIG_DISCOVERY_CLIENT) .addSchemaInterface(ZERO_CONFIG_DISCOVERY_CLIENT, DiscoveryClient.class) // add an empty instance endpoint so that can invoke by endpoint diff --git a/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistrationInstance.java b/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistrationInstance.java index fb4baa27296..739f5190a5e 100644 --- a/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistrationInstance.java +++ b/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistrationInstance.java @@ -22,14 +22,15 @@ import java.util.List; import java.util.Map; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.DataCenterProperties; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.registry.api.DataCenterInfo; import org.apache.servicecomb.registry.api.MicroserviceInstanceStatus; import org.apache.servicecomb.registry.api.RegistrationInstance; +import org.springframework.core.env.Environment; public class LocalRegistrationInstance implements RegistrationInstance { - private final MicroserviceProperties microserviceProperties; + private final Environment environment; private final DataCenterInfo dataCenterInfo; @@ -42,18 +43,16 @@ public class LocalRegistrationInstance implements RegistrationInstance { private final Map properties = new HashMap<>(); public LocalRegistrationInstance( - MicroserviceProperties microserviceProperties, + Environment environment, DataCenterProperties dataCenterProperties) { - this.microserviceProperties = microserviceProperties; + this.environment = environment; this.dataCenterInfo = new DataCenterInfo(); this.dataCenterInfo.setName(dataCenterProperties.getName()); this.dataCenterInfo.setRegion(dataCenterProperties.getRegion()); this.dataCenterInfo.setAvailableZone(dataCenterProperties.getAvailableZone()); - if (this.microserviceProperties.getProperties() != null) { - this.properties.putAll(this.microserviceProperties.getProperties()); - } + this.properties.putAll(BootStrapProperties.readServiceProperties(environment)); this.instanceId = System.currentTimeMillis() + "-" + ManagementFactory.getRuntimeMXBean().getPid(); @@ -61,27 +60,27 @@ public LocalRegistrationInstance( @Override public String getEnvironment() { - return microserviceProperties.getEnvironment(); + return BootStrapProperties.readServiceEnvironment(environment); } @Override public String getApplication() { - return microserviceProperties.getApplication(); + return BootStrapProperties.readApplication(environment); } @Override public String getServiceName() { - return microserviceProperties.getName(); + return BootStrapProperties.readServiceName(environment); } @Override public String getAlias() { - return microserviceProperties.getAlias(); + return BootStrapProperties.readServiceAlias(environment); } @Override public String getVersion() { - return microserviceProperties.getVersion(); + return BootStrapProperties.readServiceVersion(environment); } @Override @@ -91,7 +90,7 @@ public DataCenterInfo getDataCenterInfo() { @Override public String getDescription() { - return microserviceProperties.getDescription(); + return BootStrapProperties.readServiceDescription(environment); } @Override diff --git a/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistryConfiguration.java b/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistryConfiguration.java index 8fe7fedb311..776fa12f3e0 100644 --- a/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistryConfiguration.java +++ b/service-registry/registry-local/src/main/java/org/apache/servicecomb/localregistry/LocalRegistryConfiguration.java @@ -17,17 +17,17 @@ package org.apache.servicecomb.localregistry; import org.apache.servicecomb.config.DataCenterProperties; -import org.apache.servicecomb.config.MicroserviceProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; @Configuration public class LocalRegistryConfiguration { @Bean public LocalRegistrationInstance localRegistrationInstance( - MicroserviceProperties microserviceProperties, + Environment environment, DataCenterProperties dataCenterProperties) { - return new LocalRegistrationInstance(microserviceProperties, dataCenterProperties); + return new LocalRegistrationInstance(environment, dataCenterProperties); } @Bean diff --git a/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosMicroserviceHandler.java b/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosMicroserviceHandler.java index cada738df5f..8f1e66ac1fd 100644 --- a/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosMicroserviceHandler.java +++ b/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosMicroserviceHandler.java @@ -24,8 +24,8 @@ import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.ConfigUtil; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.foundation.common.net.NetUtils; import org.springframework.core.env.Environment; @@ -46,8 +46,7 @@ public class NacosMicroserviceHandler { private static final String INSTANCE_PROPS = "SERVICECOMB_INSTANCE_PROPS"; - public static Instance createMicroserviceInstance(NacosDiscoveryProperties properties, Environment environment, - MicroserviceProperties microserviceProperties) { + public static Instance createMicroserviceInstance(NacosDiscoveryProperties properties, Environment environment) { Instance instance = new Instance(); instance.setIp(StringUtils.isEmpty(properties.getIp()) ? NetUtils.getHostName() : properties.getIp()); instance.setPort(getEnvPort(environment)); @@ -55,9 +54,9 @@ public static Instance createMicroserviceInstance(NacosDiscoveryProperties prope instance.setWeight(properties.getWeight()); instance.setEnabled(properties.isInstanceEnabled()); Map metadata = properties.getMetadata(); - metadata.put("version", microserviceProperties.getVersion()); - metadata.put("alias", microserviceProperties.getAlias()); - metadata.put("description", microserviceProperties.getDescription()); + metadata.put("version", BootStrapProperties.readServiceVersion(environment)); + metadata.put("alias", BootStrapProperties.readServiceAlias(environment)); + metadata.put("description", BootStrapProperties.readServiceDescription(environment)); metadata.put("secure", String.valueOf(properties.isSecure())); if (!StringUtils.isEmpty(environment.getProperty(VERSION_MAPPING)) && !StringUtils.isEmpty(environment.getProperty(environment.getProperty(VERSION_MAPPING)))) { @@ -67,7 +66,7 @@ public static Instance createMicroserviceInstance(NacosDiscoveryProperties prope instance.setMetadata(metadata); instance.setClusterName(properties.getClusterName()); instance.setEphemeral(properties.isEphemeral()); - instance.setServiceName(microserviceProperties.getName()); + instance.setServiceName(BootStrapProperties.readServiceName(environment)); return instance; } diff --git a/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistration.java b/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistration.java index 68c1a158048..754a05f709c 100644 --- a/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistration.java +++ b/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistration.java @@ -20,7 +20,7 @@ import java.util.List; import java.util.Map; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.registry.api.MicroserviceInstanceStatus; import org.apache.servicecomb.registry.api.Registration; import org.springframework.beans.factory.annotation.Autowired; @@ -50,8 +50,6 @@ public class NacosRegistration implements Registration schemas, Map if (CollectionUtils.isEmpty(schemas)) { return; } - for (Map.Entry entry: schemas.entrySet()) { + for (Map.Entry entry : schemas.entrySet()) { metadata.put(NacosConst.SCHEMA_PREFIX + entry.getKey(), entry.getValue()); } } diff --git a/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistrationInstance.java b/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistrationInstance.java index d2442072a56..9bb3013c0fd 100644 --- a/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistrationInstance.java +++ b/service-registry/registry-nacos/src/main/java/org/apache/servicecomb/registry/nacos/NacosRegistrationInstance.java @@ -22,10 +22,11 @@ import java.util.List; import java.util.Map; -import org.apache.servicecomb.config.MicroserviceProperties; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.registry.api.DataCenterInfo; import org.apache.servicecomb.registry.api.MicroserviceInstanceStatus; import org.apache.servicecomb.registry.api.RegistrationInstance; +import org.springframework.core.env.Environment; import com.alibaba.nacos.api.naming.pojo.Instance; @@ -38,13 +39,13 @@ public class NacosRegistrationInstance implements RegistrationInstance { private final List endpoints = new ArrayList<>(); - private final MicroserviceProperties microserviceProperties; + private final Environment environment; public NacosRegistrationInstance(Instance instance, NacosDiscoveryProperties nacosDiscoveryProperties, - MicroserviceProperties microserviceProperties) { + Environment environment) { this.instance = instance; this.nacosDiscoveryProperties = nacosDiscoveryProperties; - this.microserviceProperties = microserviceProperties; + this.environment = environment; } @Override @@ -54,17 +55,17 @@ public String getEnvironment() { @Override public String getApplication() { - return microserviceProperties.getApplication(); + return BootStrapProperties.readApplication(environment); } @Override public String getServiceName() { - return microserviceProperties.getName(); + return BootStrapProperties.readServiceName(environment); } @Override public String getAlias() { - return microserviceProperties.getAlias(); + return BootStrapProperties.readServiceAlias(environment); } @Override @@ -82,7 +83,7 @@ public DataCenterInfo getDataCenterInfo() { @Override public String getDescription() { - return microserviceProperties.getDescription(); + return BootStrapProperties.readServiceDescription(environment); } @Override diff --git a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/MicroserviceHandler.java b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/MicroserviceHandler.java index 92abac9c9ab..c9fc2810629 100644 --- a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/MicroserviceHandler.java +++ b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/MicroserviceHandler.java @@ -23,9 +23,9 @@ import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; +import org.apache.servicecomb.config.BootStrapProperties; import org.apache.servicecomb.config.ConfigUtil; import org.apache.servicecomb.config.DataCenterProperties; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.foundation.common.net.NetUtils; import org.apache.servicecomb.service.center.client.model.DataCenterInfo; import org.apache.servicecomb.service.center.client.model.Framework; @@ -59,30 +59,28 @@ public class MicroserviceHandler { private static final String INSTANCE_PROPS = "SERVICECOMB_INSTANCE_PROPS"; public static Microservice createMicroservice( - Environment environment, - SCConfigurationProperties bootstrapProperties, - MicroserviceProperties microserviceProperties) { + Environment environment) { Microservice microservice = new Microservice(); - microservice.setProperties(microserviceProperties.getProperties()); + microservice.setProperties(BootStrapProperties.readServiceProperties(environment)); if (!StringUtils.isEmpty(environment.getProperty(APP_MAPPING)) && !StringUtils.isEmpty(environment.getProperty(environment.getProperty(APP_MAPPING)))) { microservice.setAppId(environment.getProperty(environment.getProperty(APP_MAPPING))); } else { - microservice.setAppId(microserviceProperties.getApplication()); + microservice.setAppId(BootStrapProperties.readApplication(environment)); } if (!StringUtils.isEmpty(environment.getProperty(SERVICE_MAPPING)) && !StringUtils.isEmpty(environment.getProperty(environment.getProperty(SERVICE_MAPPING)))) { microservice.setServiceName(environment.getProperty(environment.getProperty(SERVICE_MAPPING))); } else { - microservice.setServiceName(microserviceProperties.getName()); + microservice.setServiceName(BootStrapProperties.readServiceName(environment)); } if (!StringUtils.isEmpty(environment.getProperty(VERSION_MAPPING)) && !StringUtils.isEmpty(environment.getProperty(environment.getProperty(VERSION_MAPPING)))) { microservice.setVersion(environment.getProperty(environment.getProperty(VERSION_MAPPING))); } else { - microservice.setVersion(microserviceProperties.getVersion()); + microservice.setVersion(BootStrapProperties.readServiceVersion(environment)); } - microservice.setEnvironment(microserviceProperties.getEnvironment()); + microservice.setEnvironment(BootStrapProperties.readServiceEnvironment(environment)); Framework framework = createFramework(); microservice.setFramework(framework); @@ -106,7 +104,6 @@ private static Framework createFramework() { public static MicroserviceInstance createMicroserviceInstance( Environment environment, SCConfigurationProperties scConfigurationProperties, - MicroserviceProperties microserviceProperties, DataCenterProperties dataCenterProperties) { MicroserviceInstance microserviceInstance = new MicroserviceInstance(); String hostName = StringUtils.isEmpty(scConfigurationProperties.getHostname()) ? NetUtils.getHostName() @@ -138,11 +135,11 @@ public static MicroserviceInstance createMicroserviceInstance( !StringUtils.isEmpty(environment.getProperty(environment.getProperty(VERSION_MAPPING)))) { microserviceInstance.setVersion(environment.getProperty(environment.getProperty(VERSION_MAPPING))); } else { - microserviceInstance.setVersion(microserviceProperties.getVersion()); + microserviceInstance.setVersion(BootStrapProperties.readServiceVersion(environment)); } Map properties = new HashMap<>(); - properties.putAll(microserviceProperties.getProperties()); + properties.putAll(BootStrapProperties.readServiceProperties(environment)); properties.putAll(genCasProperties(environment)); microserviceInstance.setProperties(properties); microserviceInstance.setStatus(MicroserviceInstanceStatus.valueOf(scConfigurationProperties.getInitialStatus())); diff --git a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCAddressManager.java b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCAddressManager.java index efc66140f98..c9bf300a36f 100644 --- a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCAddressManager.java +++ b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCAddressManager.java @@ -24,7 +24,6 @@ import java.util.Map; import java.util.Set; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.foundation.common.event.EventManager; import org.apache.servicecomb.http.client.event.RefreshEndpointEvent; import org.apache.servicecomb.service.center.client.RegistrationEvents.HeartBeatEvent; @@ -54,17 +53,13 @@ public enum Type { private final ServiceCenterClient serviceCenterClient; - private final MicroserviceProperties microserviceProperties; - private final SCRegistration scRegistration; private final SCConfigurationProperties configurationProperties; - public SCAddressManager(MicroserviceProperties microserviceProperties, - SCConfigurationProperties configurationProperties, + public SCAddressManager(SCConfigurationProperties configurationProperties, ServiceCenterClient serviceCenterClient, SCRegistration scRegistration) { - this.microserviceProperties = microserviceProperties; this.configurationProperties = configurationProperties; this.serviceCenterClient = serviceCenterClient; this.scRegistration = scRegistration; diff --git a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCConfiguration.java b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCConfiguration.java index 8b516cfd9a5..ac7620ad203 100644 --- a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCConfiguration.java +++ b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCConfiguration.java @@ -18,7 +18,6 @@ import java.util.List; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.foundation.auth.AuthHeaderProvider; import org.apache.servicecomb.service.center.client.ServiceCenterClient; import org.apache.servicecomb.service.center.client.ServiceCenterWatch; @@ -67,11 +66,11 @@ public SCDiscovery scDiscovery( } @Bean - public SCAddressManager scAddressManager(MicroserviceProperties microserviceProperties, + public SCAddressManager scAddressManager( @Qualifier("scConfigurationProperties") SCConfigurationProperties scConfigurationProperties, SCRegistration scRegistration, @Qualifier("serviceCenterClient") ServiceCenterClient serviceCenterClient) { - return new SCAddressManager(microserviceProperties, scConfigurationProperties, + return new SCAddressManager(scConfigurationProperties, serviceCenterClient, scRegistration); } } diff --git a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCRegistration.java b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCRegistration.java index fda0273ca31..ba7047632c9 100644 --- a/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCRegistration.java +++ b/service-registry/registry-service-center/src/main/java/org/apache/servicecomb/registry/sc/SCRegistration.java @@ -20,7 +20,6 @@ import java.util.concurrent.TimeUnit; import org.apache.servicecomb.config.DataCenterProperties; -import org.apache.servicecomb.config.MicroserviceProperties; import org.apache.servicecomb.foundation.common.event.SimpleEventBus; import org.apache.servicecomb.registry.api.MicroserviceInstanceStatus; import org.apache.servicecomb.registry.api.Registration; @@ -57,8 +56,6 @@ public class SCRegistration implements Registration { private SCRegistrationInstance registrationInstance; - private MicroserviceProperties microserviceProperties; - private DataCenterProperties dataCenterProperties; private Environment environment; @@ -73,11 +70,6 @@ public SCRegistration(SCConfigurationProperties configurationProperties, this.serviceCenterWatch = serviceCenterWatch; } - @Autowired - public void setMicroserviceProperties(MicroserviceProperties microserviceProperties) { - this.microserviceProperties = microserviceProperties; - } - @Autowired public void setDataCenterProperties(DataCenterProperties dataCenterProperties) { this.dataCenterProperties = dataCenterProperties; @@ -92,11 +84,10 @@ public void setEnvironment(Environment environment) { @Override public void init() { microservice = MicroserviceHandler.createMicroservice( - environment, configurationProperties, microserviceProperties); + environment); microserviceInstance = MicroserviceHandler.createMicroserviceInstance( environment, configurationProperties, - microserviceProperties, dataCenterProperties); serviceCenterRegistration = new ServiceCenterRegistration(serviceCenterClient, new ServiceCenterConfiguration().setCanOverwriteSwagger( diff --git a/solutions/solution-basic/src/main/java/org/apache/servicecomb/solution/basic/health/HealthEndpoint.java b/solutions/solution-basic/src/main/java/org/apache/servicecomb/solution/basic/health/HealthEndpoint.java index aae8aa48d6c..641a35ed60e 100644 --- a/solutions/solution-basic/src/main/java/org/apache/servicecomb/solution/basic/health/HealthEndpoint.java +++ b/solutions/solution-basic/src/main/java/org/apache/servicecomb/solution/basic/health/HealthEndpoint.java @@ -30,5 +30,6 @@ public interface HealthEndpoint { * the target instance is alive. */ @GET + @Path("/health") boolean health(@QueryParam("instanceId") String instanceId, @QueryParam("registryName") String registryName); }