From 7f2a3307d64e4a789a5d091cded9bb64fbfa0535 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E5=BB=B6?= <1060026287@qq.com> Date: Tue, 24 Nov 2020 11:17:13 +0800 Subject: [PATCH] [ISSUE-#4256] Just inject environment in StartingSpringApplicationRunListener (#4257) * just inject environment in StartingSpringApplicationRunListener * make nacosStartingListener is decoupling with springApplicationRunListener. * add api doc * refactor. transfer nacos listeners to SpringApplicationRunListener. * remove unuseful import * add doc info --- .../config/server/utils/PropertyUtil.java | 1 - .../code/SpringApplicationRunListener.java | 113 ++++++++++++++ .../StandaloneProfileApplicationListener.java | 3 +- .../LoggingApplicationListener.java} | 38 +---- .../listener/NacosApplicationListener.java | 78 ++++++++++ .../StartingApplicationListener.java} | 139 +++++++++--------- .../main/resources/META-INF/logback/nacos.xml | 2 +- .../main/resources/META-INF/spring.factories | 3 +- distribution/conf/nacos-logback.xml | 2 +- 9 files changed, 274 insertions(+), 105 deletions(-) create mode 100644 core/src/main/java/com/alibaba/nacos/core/code/SpringApplicationRunListener.java rename core/src/main/java/com/alibaba/nacos/core/{code/LoggingSpringApplicationRunListener.java => listener/LoggingApplicationListener.java} (67%) create mode 100644 core/src/main/java/com/alibaba/nacos/core/listener/NacosApplicationListener.java rename core/src/main/java/com/alibaba/nacos/core/{code/StartingSpringApplicationRunListener.java => listener/StartingApplicationListener.java} (88%) diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java index 320104de92a..daf7a3774c0 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/utils/PropertyUtil.java @@ -326,7 +326,6 @@ public String getProperty(String key, String defaultValue) { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - EnvUtil.setEnvironment(configurableApplicationContext.getEnvironment()); loadSetting(); } } diff --git a/core/src/main/java/com/alibaba/nacos/core/code/SpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/code/SpringApplicationRunListener.java new file mode 100644 index 00000000000..43b1477b262 --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/code/SpringApplicationRunListener.java @@ -0,0 +1,113 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 com.alibaba.nacos.core.code; + +import com.alibaba.nacos.core.listener.LoggingApplicationListener; +import com.alibaba.nacos.core.listener.NacosApplicationListener; +import com.alibaba.nacos.core.listener.StartingApplicationListener; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.event.EventPublishingRunListener; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; + +import java.util.ArrayList; +import java.util.List; + +/** + * {@link org.springframework.boot.SpringApplicationRunListener} before {@link EventPublishingRunListener} execution. + * + * @author Mercy + * @since 0.2.2 + */ +public class SpringApplicationRunListener implements org.springframework.boot.SpringApplicationRunListener, Ordered { + + private final SpringApplication application; + + private final String[] args; + + private List nacosApplicationListeners = new ArrayList<>(); + + { + nacosApplicationListeners.add(new LoggingApplicationListener()); + nacosApplicationListeners.add(new StartingApplicationListener()); + } + + public SpringApplicationRunListener(SpringApplication application, String[] args) { + this.application = application; + this.args = args; + } + + @Override + public void starting() { + for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) { + nacosApplicationListener.starting(); + } + } + + @Override + public void environmentPrepared(ConfigurableEnvironment environment) { + for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) { + nacosApplicationListener.environmentPrepared(environment); + } + } + + @Override + public void contextPrepared(ConfigurableApplicationContext context) { + for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) { + nacosApplicationListener.contextPrepared(context); + } + } + + @Override + public void contextLoaded(ConfigurableApplicationContext context) { + for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) { + nacosApplicationListener.contextLoaded(context); + } + } + + @Override + public void started(ConfigurableApplicationContext context) { + for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) { + nacosApplicationListener.started(context); + } + } + + @Override + public void running(ConfigurableApplicationContext context) { + for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) { + nacosApplicationListener.running(context); + } + } + + @Override + public void failed(ConfigurableApplicationContext context, Throwable exception) { + for (NacosApplicationListener nacosApplicationListener : nacosApplicationListeners) { + nacosApplicationListener.failed(context, exception); + } + } + + /** + * Before {@link EventPublishingRunListener}. + * + * @return HIGHEST_PRECEDENCE + */ + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE; + } +} diff --git a/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java b/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java index f22f98fd3f9..43ab8f3615a 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java @@ -46,8 +46,7 @@ public class StandaloneProfileApplicationListener public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); - EnvUtil.setEnvironment(environment); - + if (environment.getProperty(STANDALONE_MODE_PROPERTY_NAME, boolean.class, false)) { environment.addActiveProfile(STANDALONE_SPRING_PROFILE); } diff --git a/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/LoggingApplicationListener.java similarity index 67% rename from core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java rename to core/src/main/java/com/alibaba/nacos/core/listener/LoggingApplicationListener.java index 7e6d23bc938..d0968b13b3e 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/listener/LoggingApplicationListener.java @@ -14,49 +14,35 @@ * limitations under the License. */ -package com.alibaba.nacos.core.code; +package com.alibaba.nacos.core.listener; -import com.alibaba.nacos.sys.env.EnvUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.SpringApplicationRunListener; -import org.springframework.boot.context.event.EventPublishingRunListener; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import static org.springframework.boot.context.logging.LoggingApplicationListener.CONFIG_PROPERTY; import static org.springframework.core.io.ResourceLoader.CLASSPATH_URL_PREFIX; /** - * Logging {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution. + * For init logging configuration. * - * @author Mercy - * @since 0.2.2 + * @author horizonzy + * @since 1.4.1 */ -public class LoggingSpringApplicationRunListener implements SpringApplicationRunListener, Ordered { +public class LoggingApplicationListener implements NacosApplicationListener { private static final String DEFAULT_NACOS_LOGBACK_LOCATION = CLASSPATH_URL_PREFIX + "META-INF/logback/nacos.xml"; - private static final Logger LOGGER = LoggerFactory.getLogger(LoggingSpringApplicationRunListener.class); - - private final SpringApplication application; - - private final String[] args; - - public LoggingSpringApplicationRunListener(SpringApplication application, String[] args) { - this.application = application; - this.args = args; - } + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingApplicationListener.class); @Override public void starting() { + } @Override public void environmentPrepared(ConfigurableEnvironment environment) { - EnvUtil.setEnvironment(environment); if (!environment.containsProperty(CONFIG_PROPERTY)) { System.setProperty(CONFIG_PROPERTY, DEFAULT_NACOS_LOGBACK_LOCATION); if (LOGGER.isInfoEnabled()) { @@ -91,14 +77,4 @@ public void running(ConfigurableApplicationContext context) { public void failed(ConfigurableApplicationContext context, Throwable exception) { } - - /** - * Before {@link EventPublishingRunListener}. - * - * @return HIGHEST_PRECEDENCE - */ - @Override - public int getOrder() { - return HIGHEST_PRECEDENCE; - } } diff --git a/core/src/main/java/com/alibaba/nacos/core/listener/NacosApplicationListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/NacosApplicationListener.java new file mode 100644 index 00000000000..08f74f5551f --- /dev/null +++ b/core/src/main/java/com/alibaba/nacos/core/listener/NacosApplicationListener.java @@ -0,0 +1,78 @@ +/* + * Copyright 1999-2018 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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 com.alibaba.nacos.core.listener; + +import com.alibaba.nacos.core.code.SpringApplicationRunListener; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.ConfigurableEnvironment; + +/** + * Nacos Application Listener, execute init process. + * + * @author horizonzy + * @since 1.4.1 + */ +public interface NacosApplicationListener { + + /** + * {@link SpringApplicationRunListener#starting}. + */ + void starting(); + + /** + * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#environmentPrepared}. + * + * @param environment environment + */ + void environmentPrepared(ConfigurableEnvironment environment); + + /** + * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#contextLoaded}. + * + * @param context context + */ + void contextPrepared(ConfigurableApplicationContext context); + + /** + * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#contextLoaded}. + * + * @param context context + */ + void contextLoaded(ConfigurableApplicationContext context); + + /** + * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#started}. + * + * @param context context + */ + void started(ConfigurableApplicationContext context); + + /** + * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#running}. + * + * @param context context + */ + void running(ConfigurableApplicationContext context); + + /** + * {@link com.alibaba.nacos.core.code.SpringApplicationRunListener#failed}. + * + * @param context context + * @param exception exception + */ + void failed(ConfigurableApplicationContext context, Throwable exception); +} diff --git a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/listener/StartingApplicationListener.java similarity index 88% rename from core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java rename to core/src/main/java/com/alibaba/nacos/core/listener/StartingApplicationListener.java index 6a022e9f71a..7ab149564ae 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/listener/StartingApplicationListener.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.alibaba.nacos.core.code; +package com.alibaba.nacos.core.listener; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; @@ -28,12 +28,8 @@ import com.alibaba.nacos.sys.utils.InetUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.SpringApplicationRunListener; -import org.springframework.boot.context.event.EventPublishingRunListener; import org.springframework.boot.env.OriginTrackedMapPropertySource; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import java.io.File; @@ -44,14 +40,14 @@ import java.util.concurrent.TimeUnit; /** - * Logging starting message {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution. + * init environment config. * * @author hxy1991 * @since 0.5.0 */ -public class StartingSpringApplicationRunListener implements SpringApplicationRunListener, Ordered { +public class StartingApplicationListener implements NacosApplicationListener { - private static final Logger LOGGER = LoggerFactory.getLogger(StartingSpringApplicationRunListener.class); + private static final Logger LOGGER = LoggerFactory.getLogger(StartingApplicationListener.class); private static final String MODE_PROPERTY_KEY_STAND_MODE = "nacos.mode"; @@ -63,10 +59,6 @@ public class StartingSpringApplicationRunListener implements SpringApplicationRu private volatile boolean starting; - public StartingSpringApplicationRunListener(SpringApplication application, String[] args) { - - } - @Override public void starting() { starting = true; @@ -74,32 +66,17 @@ public void starting() { @Override public void environmentPrepared(ConfigurableEnvironment environment) { - EnvUtil.setEnvironment(environment); - try { - environment.getPropertySources().addLast(new OriginTrackedMapPropertySource("first_pre", - EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource()))); - } catch (IOException e) { - throw new NacosRuntimeException(NacosException.SERVER_ERROR, e); - } - if (EnvUtil.getStandaloneMode()) { - System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "stand alone"); - } else { - System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "cluster"); - } - if (EnvUtil.getFunctionMode() == null) { - System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, "All"); - } else if (EnvUtil.FUNCTION_MODE_CONFIG.equals(EnvUtil.getFunctionMode())) { - System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_CONFIG); - } else if (EnvUtil.FUNCTION_MODE_NAMING.equals(EnvUtil.getFunctionMode())) { - System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_NAMING); - } + injectEnvironment(environment); - System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIP()); + loadPreProperties(environment); + + initSystemProperty(); } @Override public void contextPrepared(ConfigurableApplicationContext context) { logClusterConf(); + logStarting(); } @@ -111,36 +88,17 @@ public void contextLoaded(ConfigurableApplicationContext context) { @Override public void started(ConfigurableApplicationContext context) { starting = false; - ConfigurableEnvironment env = context.getEnvironment(); closeExecutor(); logFilePath(); - // External data sources are used by default in cluster mode - boolean useExternalStorage = ("mysql".equalsIgnoreCase(env.getProperty("spring.datasource.platform", ""))); - - // must initialize after setUseExternalDB - // This value is true in stand-alone mode and false in cluster mode - // If this value is set to true in cluster mode, nacos's distributed storage engine is turned on - // default value is depend on ${nacos.standalone} - - if (!useExternalStorage) { - boolean embeddedStorage = EnvUtil.getStandaloneMode() || Boolean.getBoolean("embeddedStorage"); - // If the embedded data source storage is not turned on, it is automatically - // upgraded to the external data source storage, as before - if (!embeddedStorage) { - useExternalStorage = true; - } - } - - LOGGER.info("Nacos started successfully in {} mode. use {} storage", - System.getProperty(MODE_PROPERTY_KEY_STAND_MODE), useExternalStorage ? "external" : "embedded"); + judgeStorageMode(context.getEnvironment()); } @Override public void running(ConfigurableApplicationContext context) { - EnvUtil.getEnvironment().getPropertySources().remove("first_pre"); + removePreProperties(context.getEnvironment()); } @Override @@ -162,14 +120,38 @@ public void failed(ConfigurableApplicationContext context, Throwable exception) Paths.get(EnvUtil.getNacosHome(), "logs/nacos.log")); } - /** - * Before {@link EventPublishingRunListener}. - * - * @return HIGHEST_PRECEDENCE - */ - @Override - public int getOrder() { - return HIGHEST_PRECEDENCE; + private void injectEnvironment(ConfigurableEnvironment environment) { + EnvUtil.setEnvironment(environment); + } + + private void loadPreProperties(ConfigurableEnvironment environment) { + try { + environment.getPropertySources().addLast(new OriginTrackedMapPropertySource("first_pre", + EnvUtil.loadProperties(EnvUtil.getApplicationConfFileResource()))); + } catch (IOException e) { + throw new NacosRuntimeException(NacosException.SERVER_ERROR, e); + } + } + + private void initSystemProperty() { + if (EnvUtil.getStandaloneMode()) { + System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "stand alone"); + } else { + System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "cluster"); + } + if (EnvUtil.getFunctionMode() == null) { + System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, "All"); + } else if (EnvUtil.FUNCTION_MODE_CONFIG.equals(EnvUtil.getFunctionMode())) { + System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_CONFIG); + } else if (EnvUtil.FUNCTION_MODE_NAMING.equals(EnvUtil.getFunctionMode())) { + System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, EnvUtil.FUNCTION_MODE_NAMING); + } + + System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIP()); + } + + private void removePreProperties(ConfigurableEnvironment environment) { + environment.getPropertySources().remove("first_pre"); } private void logClusterConf() { @@ -183,6 +165,12 @@ private void logClusterConf() { } } + private void closeExecutor() { + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdownNow(); + } + } + private void logFilePath() { String[] dirNames = new String[] {"logs", "conf", "data"}; for (String dirName : dirNames) { @@ -195,12 +183,6 @@ private void logFilePath() { } } - private void closeExecutor() { - if (scheduledExecutorService != null) { - scheduledExecutorService.shutdownNow(); - } - } - private void logStarting() { if (!EnvUtil.getStandaloneMode()) { @@ -214,4 +196,27 @@ private void logStarting() { }, 1, 1, TimeUnit.SECONDS); } } + + private void judgeStorageMode(ConfigurableEnvironment env) { + + // External data sources are used by default in cluster mode + boolean useExternalStorage = ("mysql".equalsIgnoreCase(env.getProperty("spring.datasource.platform", ""))); + + // must initialize after setUseExternalDB + // This value is true in stand-alone mode and false in cluster mode + // If this value is set to true in cluster mode, nacos's distributed storage engine is turned on + // default value is depend on ${nacos.standalone} + + if (!useExternalStorage) { + boolean embeddedStorage = EnvUtil.getStandaloneMode() || Boolean.getBoolean("embeddedStorage"); + // If the embedded data source storage is not turned on, it is automatically + // upgraded to the external data source storage, as before + if (!embeddedStorage) { + useExternalStorage = true; + } + } + + LOGGER.info("Nacos started successfully in {} mode. use {} storage", + System.getProperty(MODE_PROPERTY_KEY_STAND_MODE), useExternalStorage ? "external" : "embedded"); + } } diff --git a/core/src/main/resources/META-INF/logback/nacos.xml b/core/src/main/resources/META-INF/logback/nacos.xml index 68b327681cf..00debcdd5c6 100644 --- a/core/src/main/resources/META-INF/logback/nacos.xml +++ b/core/src/main/resources/META-INF/logback/nacos.xml @@ -195,7 +195,7 @@ - + diff --git a/core/src/main/resources/META-INF/spring.factories b/core/src/main/resources/META-INF/spring.factories index c63c723f268..af6926509e2 100644 --- a/core/src/main/resources/META-INF/spring.factories +++ b/core/src/main/resources/META-INF/spring.factories @@ -3,5 +3,4 @@ org.springframework.context.ApplicationListener=\ com.alibaba.nacos.core.code.StandaloneProfileApplicationListener # SpringApplicationRunListener org.springframework.boot.SpringApplicationRunListener=\ -com.alibaba.nacos.core.code.LoggingSpringApplicationRunListener,\ -com.alibaba.nacos.core.code.StartingSpringApplicationRunListener \ No newline at end of file +com.alibaba.nacos.core.code.SpringApplicationRunListener diff --git a/distribution/conf/nacos-logback.xml b/distribution/conf/nacos-logback.xml index b4a731117ff..289a5905a9a 100644 --- a/distribution/conf/nacos-logback.xml +++ b/distribution/conf/nacos-logback.xml @@ -614,7 +614,7 @@ - +