In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to use SpringBoot integration Apollo configuration center, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
I. brief introduction
What is 1.Apollo? Apollo (Apollo) is a distributed configuration center developed by Ctrip Framework Department. The server is developed based on Spring Boot and Spring Cloud.
two。 Why use Apollo?
Security: the configuration follows the source code saved in the code base, which is easy to cause configuration leakage
Timeliness: normal configuration, configuration modification, and service restart is required to take effect.
Limitations: unable to support dynamic adjustment: for example, log switch, function switch
Second, use 1. Test project building
Note: this article mainly introduces the dynamic configuration of SpringBoot integrating Apollo.
1.1 add Maven dependencies
Com.ctrip.framework.apollo apollo-client 1.3.0
1.2 profile
# apollo Integration # apollo configuration application appidapp.id=springboot-apollo-demo1# apollo meta-server address, generally same as config-server address apollo.meta= http://192.168.0.153:8080# enable apollo configuration switch apollo.bootstrap.enabled=trueapollo.bootstrap.eagerLoad.enabled=true# apollo uses the configured namespace, multiple apollo.bootstrap.namespaces = application separated by commas
Configuration instructions:
App.id: the application identity information configured in the configuration center.
Apollo.bootstrap.enabled: whether to inject managed properties file configuration information into the Spring container during the application startup phase.
Apollo.bootstrap.eagerLoad.enabled: load the Apollo configuration before initializing the logging system.
Apollo.bootstrap.namespaces: the configured namespace, separated by multiple commas, and a namespace is equivalent to a configuration file.
* * apollo.meta:** current environment service configuration address. It is recommended to have at least two nodes in the production environment. You can enter multiple commas to separate and use a single domain, such as http://config.xxx.com (supported by software load balancers such as nginx), instead of multiple IP addresses, because the server may expand or shrink.
The illustration shows:
1.3 add Startup Class
@ SpringBootApplication (exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class}) public class SpringbootApolloApplication {public static void main (String [] args) {SpringApplication.run (SpringbootApolloApplication.class, args);}}
1.4 add configuration switch class
Configuration based on @ Value annotations
@ Componentpublic class ValueStyleProperty {@ Value ("${apollo.value.demoKey1}") private String demoKey1; @ Value ("${apollo.value.demoKey2}") private String demoKey2; / / omit the get/set method}
1.5 add test controller
/ * value annotation method, get the attribute * * @ author mengqiang * / @ RestController@RequestMapping ("/ value-style") public class ValuePropertyController {@ Autowired private ValueStyleProperty keyProperty; @ Value ("${server.port}") private String port; @ Value ("${apollo.bootstrap.namespaces:'application'}") private String namespaces; @ GetMapping ("/ get") public Map getProperty () {Map map = new LinkedHashMap () Map.put ("port", port); map.put ("namespaces", namespaces); map.put ("demoKey1", keyProperty.getDemoKey1 ()); map.put ("demoKey2", keyProperty.getDemoKey2 ()); return map;} 2. Configuration of Apollo configuration Center
2.1 create a project
2.2 fill in the configuration information
Configuration instructions:
Department: select the department where the application is located. (customizable department)
Application AppId: the unique id used to identify the identity of the application, in the format of string, which must be consistent with the app.id configured in application.properties.
Application name: application name, used for interface display only.
Person in charge of the application: the selected person will become the administrator of the project by default, with permissions such as project permission management, cluster creation, Namespace creation and so on.
Screenshot of the project configuration home page
2.3 add configuration
2.3.1 add individually in tabular form
Note: batch operation is not allowed.
2.3.2 batch addition in text form
Note: batch operation can be realized.
2.4 release configuration
Note: the configuration will not take effect until it is released
Click the publish button
2.5 simultaneous configuration of multiple environments
Note:
Through the synchronization configuration feature, you can keep the configuration of multiple environments and clusters consistent. It should be noted that after synchronization is completed, it will not take effect for the application until it is released.
Click synchronize configuration
Select the configuration that needs to be synchronized, and the target environment
Click sync
Target environment view
3. Project initiation and testing
3.1 initial start read test
3.2 automatically update property tests
Console changes after release
Test output value change
4. Common integration problems
The problem that 4.1@ConfigurationProperties annotation integration Apollo is not effective
Sample configuration class
/ * Public switch, key value attribute configuration * * @ author mengqiang * / @ Component@ConfigurationProperties (prefix = "apollo.first.config") public class ConfigFirstProperty {/ * * Test digit * / private Integer oneNumber; / * * Test string * / private String oneStr; / * * enable tag * / private Boolean oneEnableFlag / * * default tax rate is 0.03 * / private BigDecimal oneTaxRate = new BigDecimal ("0.03"); / / omit get/set method}
Solution
Add a monitoring configuration
Import com.ctrip.framework.apollo.model.ConfigChange;import com.ctrip.framework.apollo.model.ConfigChangeEvent;import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;import org.springframework.cloud.context.environment.EnvironmentChangeEvent / * Apollo configuration listening * / @ Configurationpublic class ApolloConfigListener implements ApplicationContextAware {/ * log * / private static final Logger LOGGER = LoggerFactory.getLogger (ApolloConfigListener.class); private ApplicationContext applicationContext / * * configure listening * ApolloConfigChangeListener > value attribute default namespace "application" * * example: @ ApolloConfigChangeListener (value = {"application", "test_space"}) * / @ ApolloConfigChangeListener private void onChange (ConfigChangeEvent changeEvent) {LOGGER.info ("[Apollo-config-change] start") For (String key: changeEvent.changedKeys ()) {ConfigChange change = changeEvent.getChange (key); LOGGER.info ("key= {}, propertyName= {}, oldValue= {}, newValue= {}", key, change.getPropertyName (), change.getOldValue (), change.getNewValue ()) } / / Update the attribute values of the corresponding bean, mainly bean this.applicationContext.publishEvent (new EnvironmentChangeEvent (changeEvent.changedKeys () with @ ConfigurationProperties annotation; LOGGER.info ("[Apollo-config-change] end");} @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}}
4.2 the log level is not updated
Sample configuration
Logging.level.com.example=info
Solution-log listener
Import com.ctrip.framework.apollo.model.ConfigChange;import com.ctrip.framework.apollo.model.ConfigChangeEvent;import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.logging.LogLevel;import org.springframework.boot.logging.LoggingSystem;import org.springframework.context.annotation.Configuration;import javax.annotation.Resource / * Apollo log-configure listening * / @ Configurationpublic class LoggerConfigListener {private static final Logger LOGGER = LoggerFactory.getLogger (LoggerConfigListener.class); private static final String LOGGER_TAG = "logging.level."; @ Resource private LoggingSystem loggingSystem / * listening log configuration changes * / @ ApolloConfigChangeListener (interestedKeyPrefixes = LOGGER_TAG) private void onChangeLogger (ConfigChangeEvent changeEvent) {LOGGER.info ("[Apollo-logger-config-change] > > start"); refreshLoggingLevel (changeEvent); LOGGER.info ("[Apollo-logger-config-change] > > end") } / * refresh log level * / private void refreshLoggingLevel (ConfigChangeEvent changeEvent) {if (null = = loggingSystem) {return;} for (String key: changeEvent.changedKeys ()) {ConfigChange change = changeEvent.getChange (key); if (! StringUtils.containsIgnoreCase (key, LOGGER_TAG)) {continue } LOGGER.info ("[Apollo-logger-config-change] > > key= {}, propertyName= {}, oldValue= {}, newValue= {}", key, change.getPropertyName (), change.getOldValue (), change.getNewValue ()); String newLevel = change.getNewValue (); LogLevel level = LogLevel.valueOf (newLevel.toUpperCase ()) LoggingSystem.setLogLevel (key.replace (LOGGER_TAG, "), level); LOGGER.info (" [Apollo-logger-config-change] > > {}-> {} ", key, newLevel);}
4.3 Log + configuration class automatically refresh integrated snooping
Note: since 4.1 and 4.2 monitor coincide, it is best to deal with them together.
Import com.ctrip.framework.apollo.model.ConfigChange;import com.ctrip.framework.apollo.model.ConfigChangeEvent;import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.BeansException;import org.springframework.boot.logging.LogLevel;import org.springframework.boot.logging.LoggingSystem;import org.springframework.cloud.context.environment.EnvironmentChangeEvent;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware Import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;/** * Apollo configuration listening * / @ Configurationpublic class ApolloConfigListener implements ApplicationContextAware {/ * log * / private static final Logger LOGGER = LoggerFactory.getLogger (ApolloConfigListener.class); / * log configuration constant * / private static final String LOGGER_TAG = "logging.level."; @ Resource private LoggingSystem loggingSystem; private ApplicationContext applicationContext @ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;} / * configuration listener * ApolloConfigChangeListener > value attribute default namespace "application" * / @ ApolloConfigChangeListener private void onChangeConfig (ConfigChangeEvent changeEvent) {LOGGER.info ("[Apollo-config-change] > > start") For (String key: changeEvent.changedKeys ()) {ConfigChange change = changeEvent.getChange (key); LOGGER.info ("[Apollo-config-change] > > key= {}, propertyName= {}, oldValue= {}, newValue= {}", key, change.getPropertyName (), change.getOldValue (), change.getNewValue ()) / / whether to configure if (StringUtils.containsIgnoreCase (key, LOGGER_TAG)) {/ / configure refresh changeLoggingLevel (key, change) for log; continue } / / Update the attribute values of the corresponding bean, mainly bean this.applicationContext.publishEvent (new EnvironmentChangeEvent (changeEvent.changedKeys () with @ ConfigurationProperties annotation;} LOGGER.info ("[Apollo-config-change] > > end") } / * refresh log level * / private void changeLoggingLevel (String key, ConfigChange change) {if (null = = loggingSystem) {return;} String newLevel = change.getNewValue (); LogLevel level = LogLevel.valueOf (newLevel.toUpperCase ()); loggingSystem.setLogLevel (key.replace (LOGGER_TAG, "), level) LOGGER.info ("[Apollo-logger-config-change] > > {}-> {}", key, newLevel);}
4.4 other questions
4.4.1 configuration file and configuration center exist at the same time, which one is enabled
When the apollo configuration switch is turned on, the configuration center configuration will override the local configuration
Note: configure the switch apollo.bootstrap.enabled=true
4.4.2 will the failure of the configuration Center affect released projects?
After the project starts, the configuration will be stored in the cache, the configuration center will hang up, and the published project will not be affected.
4.4.3 whether updating port configuration is supported
Update the port configuration is supported, but the restart must take effect, and the port occupation of the server needs to be taken into account.
The above is all the contents of the article "how to use SpringBoot Integrated Apollo configuration Center". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.