In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is the reason for choosing Spring Cloud Config as the configuration center". In the daily operation, I believe that many people have doubts about why they chose Spring Cloud Config as the configuration center. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what is the reason for choosing Spring Cloud Config as the configuration center?" Next, please follow the editor to study!
What is Spring Cloud Config?
First, the Spring Cloud Config project is a configuration solution for distributed systems. It includes two parts: Client and Server. Server provides the storage of the configuration file and provides the contents of the configuration file in the form of an interface. Client obtains data through the interface and initializes its own application according to this data.
The server, also known as the distributed configuration center, is an independent micro-service application, which is used to connect the configuration repository and provide clients with access interfaces for obtaining configuration information, encryption / decryption information and so on.
The client is each micro-service application or infrastructure in the micro-service architecture, which manages the business-related configuration content of the application resources through the designated configuration center, and obtains and loads the configuration information from the configuration center at startup.
2. Spring Cloud Config uses Git to store configuration information by default, so the configuration server built with Spring Cloud Config naturally supports version management of micro-services for configuration information, and can easily manage and access configuration content through Git client tools.
Note: in addition to using Git, Spring Cloud Config also supports other storage methods such as SVN, localized file systems, and so on. "
Basic usage of Spring Cloud Config
First, let's create a new configuration file, system-dev.properties, with the following contents
Jdbc.driverClassName: com.mysql.jdbc.Driverjdbc.url: jdbc:mysql://127.0.0.1:3306/testprojectjdbc.username: rootjdbc.password: root
Then we upload the configuration file to github,Demo address: https://github.com/Maybe728/Spring_Cloud
First, create a new SpringCloudConfigServer module
The pom.xml code is as follows:
4.0.0 com.cnblogs.hellxz ConfigServer 1.0-SNAPSHOT org.springframework.cloud spring-cloud-starter-parent Dalston.SR5 org.springframework.cloud spring-cloud-config-server org.springframework.boot Spring-boot-maven-plugin org.apache.maven.plugins maven-compiler-plugin 1.8 1.8
The configuration Center service can be activated through @ EnableConfigServer. The configuration center can do services alone or embedded in other services. It is recommended to use the configuration center as a separate service.
Package com.javaer.study;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.config.server.EnableConfigServer;/** * @ Author official account | Java Learning Tribe * * / @ SpringBootApplication@EnableConfigServerpublic class SpringCloudConfigServerApplication {public static void main (String [] args) {SpringApplication.run (SpringCloudConfigServerApplication.class, args);}}
Due to the diversity of configuration files, the following mainly describes how to configure the Git configuration form. Of course, all the configurations are configured in application.yml.
The configuration of application.yml is as follows
Spring: application: name: configserver cloud: config: server: git: # configuration file searches only the searchPaths uri: https://github.com/Maybe728/Spring_Cloud.git # corresponding to the {label} section in the url directory, that is, a branch of Git label: master # specifies the search path If you have multiple paths, use it to separate search-paths: springcloud-config-git/config-repo # for using git,svn as the back-end configuration, get the configuration file from the remote library and store it to the local file basedir: / tmp/spring-cloud-repo # the configuration center uses git from the remote git library, sometimes the local copy is contaminated If the configuration center cannot update the local configuration from the remote repository and set force-pull=true, then the local repository force-pull: true # git warehouse user name can be forced to be updated from the remote repository (public repository may not be filled in) username: # git warehouse password (public repository may not be entered) password:
Spring.cloud.config.server.git.url: specify the url address of the remote git library where the configuration file resides
Spring.cloud.config.server.git.label: a branch of Git
Spring.cloud.config.server.git.searchPaths: use with the above parameter url to locate the subdirectory of the git library. Specify the search path, or use it if there are multiple paths, separate
Spring.cloud.config.server.git.basedir: for using git,svn as the back-end configuration, getting the configuration file from the remote library needs to be stored in a local file. The default storage is in the system temporary directory, and the directory name is prefixed with config-repo-, which may be / tmp/config-repo- if it is under linux. Because the content under / tmp may be deleted by mistake, it is best to modify the storage directory for insurance. If you modify the storage directory, you can modify spring.cloud.config.server.git.basedir
Spring.cloud.config.server.git.force-pull: when the configuration center reads data from the remote git library through git, sometimes the local copy is contaminated, and the configuration center cannot update the local configuration from the remote library. If you set force-pull=true, force the local library to be updated from the remote library
Finally, after we start the program, we visit: http://localhost:8080/system-dev.properties
"success! "
Enter the following URL in the browser to access the configuration file
/ {application} / {profile} [/ {label}]
/ {application}-{profile} .yml
/ {label} / {application}-{profile} .yml
/ {application}-{profile} .properties
/ {label} / {application}-{profile} .properties
The following is an example to illustrate the meaning of the above url. If our profile name is system-dev.properties, the values corresponding to each field in URL are:
"application: system"
"profile: dev"
Build SpringCloudConfig client
After the configuration center server is configured successfully, other services obtain configuration files from the configuration center. Such services are called * * "client" * *.
Let's build a Config Client.
First create a new SpringCloudConfigClient project:
"pom.xml"
4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.1 com.javaer.study springcloudconfigclient 0.0.1-SNAPSHOT springcloudconfigclient Demo project for Spring Boot 1.8 2020.0.0 org.springframework.cloud spring-cloud-config-server org.springframework.cloud spring-cloud-starter-config org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone
Please configure the relevant configuration of the configuration center in bootstrap.yml, not with appliaction.yml.
Because when the service starts, it will read the configuration from bootstrap, then read the configuration file from the remote configuration center, and finally get the configuration from appliaction. If there are the same configuration items, the later ones will overwrite the values read earlier.
So if the configuration of the configuration center is configured in appliaction, the configuration item will not have any effect.
"bootstrap.yml"
Server: port: 8888 spring: cloud: # the address of the configuration server config: uri: http://127.0.0.1:8080 # the value to read from the configuration file name: cloud-config # if this value is not set, the system sets this value to spring.profiles.active profile: dev # can use the previous version. The default value can be git label, branch name or commit id. Multiple Label can be used, and multiple Label can be separated by comma # label: # true: if access to the configuration center fails, stop starting the service fail-fast: true # configuration retry. The default is to retry 6 times, initially delaying retry by 1 second. If it fails again, it will delay 1.1 seconds, 1.1 seconds, 1.1 seconds, … . You can use this to configure retry: initial-interval: 2000 # maximum number of retries max-attempts: 6 # maximum retry interval max-interval: 4000 # each retry time is a multiple of the previous multiplier
The important parameters are explained as follows:
"url of the configuration center": where to read the configuration file and configure it through "spring.cloud.config.url"
"which configuration files to read are determined by the following parameters"
"spring.cloud.config.name": the name of the configuration file, corresponding to the {applicaion} value in the read URL above
"spring.cloud.config.profile": the profile of the configuration file, corresponding to the {profile} value in the URL above
"spring.cloud.config.label": you can use the previous version. The default value can be git label, branch name or commit id. Multiple Label can be used, and multiple Label can be separated by commas
"Quick failure"
If you fail to ask the client to access the configuration center, stop starting the service immediately, and set "spring.cloud.config.label" to true
"retry"
If the access configuration fails, it will automatically retry. The default is retry * * "6" times, initially delaying "1s" * * to try again. If it fails again, it will be delayed by 1.1s, 1.1s, 1.1s, ….
You can modify the value with the following parameters:
"spring.cloud.config.retry.initial-interval": failed for the first time, how long to delay the retry
"spring.cloud.config.retry.max-attempts": maximum number of retries
"spring.cloud.config.retry.max-interval": maximum retry interval
"spring.cloud.config.retry.multiplier": the retry time is a multiple of the previous one.
"if you want to implement the retry function, you need to introduce a new jar"
Org.springframework.boot spring-boot-starter-aop org.springframework.retry spring-retry
Create an object that stores configuration information after obtaining configuration information successfully
@ Componentpublic class JdbcConfigBean {@ Value ("${jdbc.url}") private String url; @ Value ("${jdbc.username}") private String username; @ Value ("${jdbc.password}") private String password; @ Value ("${jdbc.driverClassName}") private String driverClassName; public String getUrl () {return url;} public void setUrl (String url) {this.url = url } public String getUsername () {return username;} public void setUsername (String username) {this.username = username;} public String getPassword () {return password;} public void setPassword (String password) {this.password = password;} public String getDriverClassName () {return driverClassName;} public void setDriverClassName (String driverClassName) {this.driverClassName = driverClassName @ Override public String toString () {return "JdbcConfigBean [url=" + url + ", username=" + username + ", password=" + password + ", driverClassName=" + driverClassName + "]";}}
Create a Controller
Package com.javaer.study;import org.springframework.web.bind.annotation.RequestMapping;/** * @ author official account | Java Learning Tribe * * / public class SpringCloudConfigController {@ RequestMapping ("/ config") public JdbcConfigBean config () {return new JdbcConfigBean ();}}
Finally, we launch * * "SpringCloudConfigClient" * *, type http://127.0.0.1:8888/config in the browser, and you will see the configuration information.
Spring Cloud Config integrates Eureka to realize Service configuration Center
First of all, we need to build an Eureka Server, which will not go into detail, because when I explained Eureka before, the interviewer asked me: do you know what Eureka is? this time, I have not been silent and have already built it in detail. If not, you can go and have a look, by the way, add the relevant knowledge of Eureka.
Next we are going to transform the configuration center.
"transform the server"
The first step is to introduce Eureka client dependencies
Org.springframework.cloud spring-cloud-starter-netflix-eureka-client
Step 2: add the following configuration to the configuration center
Eureka: instance: preferIpAddress: true client: serviceUrl: # Register to eureka defaultZone: http://localhost:8761/eureka
The third step is to add @ EnableDiscoveryClient activation to the registry support in the startup class.
Package com.javaer.study;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.config.server.EnableConfigServer;/** * @ Author official account | Java Learning Tribe * * / @ SpringBootApplication@EnableConfigServer@EnableDiscoveryClientpublic class SpringCloudConfigServerApplication {public static void main (String [] args) {SpringApplication.run (SpringCloudConfigServerApplication.class, args);}}
"the transformation of the server is complete! "
"transform the client"
The first step is also to introduce Eureka Client dependencies
Org.springframework.cloud spring-cloud-starter-netflix-eureka-client
Step 2 modify the configuration
Eureka: client: serviceUrl: # points to the address of the registry defaultZone: http://127.0.0.1:8761/eureka instance: preferIpAddress: trueserver: port: 8888spring: cloud: # the address of the configuration server config: uri: http://127.0.0.1:8080 username: user password: 111111 # the value to read from the configuration file Name: system # if you don't set this value Then the system sets this value to spring.profiles.active profile: dev discovery: # to enable service discovery. The previous version can be used from the specified config service address to the registry service ID enabled: true serviceId: config-serve #. The default value can be git label, branch name or commit id. Multiple Label can be used, and multiple Label can be separated by comma # label: # true: if access to the configuration center fails, stop starting the service fail-fast: true # configuration retry. The default is to retry 6 times, initially delaying retry by 1 second. If it fails again, it will delay 1.1 seconds, 1.1 seconds, 1.1 seconds, … . You can use this to configure retry: initial-interval: 2000 # maximum number of retries max-attempts: 6 # maximum retry interval max-interval: 4000 # each retry time is a multiple of the previous multiplier
The final step is to add @ EnableDiscoveryClient to activate registry support in the startup class.
"client transformation completed! "
Spring Cloud Config health check
Config Server comes with a health status indicator to check whether the configured EnvironmentRepository is working properly.
The current health status can be queried using the / health endpoint of Config Server.
By default, the {application} requested by the health indicator to the EnvironmentRepository is app, and {profile} and {label} are the default values for the corresponding EnvironmentRepository implementation.
For Git, {profile} is default and {label} is master.
Spring Cloud Config attribute override
Config Server has a "property override" feature that allows developers to provide configuration properties for all applications. You only need to set the parameters of the key-value pair through the spring.cloud.config.server.overrides property, which will be loaded into the client configuration as Map.
Using this feature, you can easily configure some common or default properties for Spring Cloud applications.
The parameters configured through this property (priority is higher than the configuration in the Git repository) will not be modified by the client of Spring Cloud.
All Spring Cloud clients get configuration information when they get it from Config Server.
Spring Cloud Config security protection
We know that, generally speaking, the information of the configuration center is very sensitive and confidential, such as the configuration of database account password, the configuration of redis account password and so on, so it is very necessary to protect the configuration information.
Because microservices are built on top of Spring Boot, integrating Spring Security is the most convenient way.
First, the Spring Security dependency is introduced on the server side.
Org.springframework.boot spring-boot-starter-security
Then add the Spring Security configuration to the configuration file
Security: basic: enabled: true # enable basic authentication (default) user: # configure security username password, default "user" username and randomly generated password name: user password: 111111
Start the service and test it. Request http://localhost:8080/system-dev.yml, and the login screen will appear.
"success! "
* * "at the same time" We are in the "SpringCloudConfigClient" project. We modify the "bootstrap.yml" configuration file (where the access information of Config Server is configured) to add authentication. We choose to add "spring.cloud.config.username" and "spring.cloud.config.password" * * attributes.
Server: port: 8888spring: cloud: # configure the address of the server config: uri: http://127.0.0.1:8080 username: user password: 111111 # the value to read from the configuration file name: system # if this value is not set, the system sets this value to spring.profiles.active profile: dev # can use the previous version. The default value can be git label, branch name or commit id. Multiple Label can be used, and multiple Label can be separated by comma # label: # true: if access to the configuration center fails, stop starting the service fail-fast: true # configuration retry. The default is to retry 6 times, initially delaying retry by 1 second. If it fails again, it will delay 1.1 seconds, 1.1 seconds, 1.1 seconds, … . You can use this configuration retry: initial-interval: 2000 # maximum number of retries max-attempts: 6 # maximum retry interval max-interval: 4000 # each retry time is a multiple of the previous multiplier: 1.2Spring Cloud Config request configuration failed quick response and retry
The client of the Spring Cloud Config preloads a lot of other information before starting to connect to the Config Server for attribute injection. When the application we build is more complex, it may take a long time to start before connecting to Config Server, and in some special scenarios, we want to quickly know whether the current application can successfully obtain configuration information from Config Server, which can reduce a lot of waiting time to start when building a debug environment in the initial stage.
First of all, if we do not start the server Config-Server, if the parameter spring.cloud.config.fail-fast=true is not configured when starting the client application directly, the client application will have loaded a lot of content, such as the Controller request, before the configuration load error.
If the spring.cloud.config.fail-fast=true parameter is configured, there will be much less preload after starting the client, and an error will be reported quickly. This effectively avoids some loading time that does not need to wait for the front when the Config-server is misconfigured, and realizes the quick return of failure information.
"this is what we call request configuration failure quick response! "
Sometimes the connection may fail due to other intermittent reasons such as network fluctuations. The Config client also provides a retry function to avoid the failure caused by some intermittent problems that lead to the start of the client application service.
To achieve this, we first need to add spring-retry and spring-boot-starter-aop dependencies in the client's * * "pom.xml" * *:
Org.springframework.retry spring-retry org.springframework.boot spring-boot-starter-aop
Then configure the failure quick response parameter.
Spring.cloud.config.fail-fast=true
Focus on configuration interpretation.
Spring.cloud.config.retry.multiplier: initial retry interval (in milliseconds), default is 1000 milliseconds
Spring.cloud.config.retry.initial-interval: the multiplier for the next interval, which defaults to 1.1 (when the initial interval is 1000 milliseconds, the next failure interval is 1100 milliseconds)
Spring.cloud.config.retry.max-interval: maximum interval, default is 2000 milliseconds
Spring.cloud.config.retry.max-attempts: maximum retry at this time, default is 6 times
How to realize dynamic refresh configuration by Spring Cloud Config
Now let's think about this question:
If we need to adjust the expiration time of the CAPTCHA from 1 minute to 2 minutes during the operation of the service, how can the server make the modified configuration take effect dynamically without restarting the service?
This is what we're going to talk about * * "dynamic refresh" * *
There are two ways to implement dynamic refresh configuration
Use Actuator
Use Spring Cloud Bus (there will be a special article later, which will not be explained again)
Next we'll use Actuator to dynamically refresh the configuration.
First of all, we add a spring-boot-starter-actuator monitoring module to the pom.xml on the client side.
Org.springframework.boot spring-boot-starter-actuator
❝
The spring-boot-starter-actuator monitoring module includes the implementation of the / refresh endpoint, which will be used to retrieve and refresh the configuration information of the client application.
❞
Then edit the application.properties file and add the following configuration to enable / refresh endpoint:
Management.endpoints.web.exposure.include=refresh
It's very simple that the client transformation is over. We just need to restart the client, and then modify the configuration information in git. When we get the configuration information again, we will find that the configuration information has been modified.
We can use / actuator/env and / actuator/refresh interfaces to dynamically update the configuration of a single service instance, but in the micro-service architecture, there may be dozens or even hundreds of service instances, so it is a bit inconvenient to call them one by one to do dynamic updates.
At this point, the study on "what is the reason for choosing Spring Cloud Config as the configuration center" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.