This article introduces the SpringCloud + Zookeeper completion configuration center and shares it with everyone, with the following:
Use scenarios
Why use zookeeper
As a distributed service framework, Zookeeper is mainly used to solve the consistency problem of application systems in distributed clusters. It can provide data storage based on directory node tree method similar to file system. Zookeeper's function is mainly used to maintain and monitor the state changes of stored data, and by monitoring the changes in these data states, it can achieve data-based cluster management.
How to use
1.pom file
<!-- Provides zookeeper integration package-><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-config</artifactId></dependency><!-- springboot provides listening--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency>
2.bootstrap.properties file
Tip: Springboot project startup will prioritize reading bootstrap.properties. Then obtain the configuration content in zookeeper before starting other configurations.
#Specify the address of zookeeper, and multiple commas are spliced spring.cloud.zookeeper.connect-string=192.168.100.0:2181#Specify springcloud Read the start position of the zookeeper path spring.cloud.zookeeper.config.root=springcloud#Start zk configuration spring.cloud.zookeeper.config.enabled=true#zk will look for the configuration in the directory named after this project in the root directory you specified. spring.application.name=service_config
3. Get the configuration in zookeeper
1.@value method:
//The value cannot be updated dynamically, the project needs to be restarted @Value("${com.xxx.username}") public String username; 2.@ConfigurationProperties and @EnableConfigurationProperties methods
//The value can be modified dynamically, and there is no need to restart @ConfigurationProperties(prefix = "com.xxx")public class UserInfo { public String username ; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }}Application code:
@SpringBootApplication//Support multiple configuration classes @EnableConfigurationProperties({xxx.class,abc.class})public class ServiceConfigApplication { public static void main(String[] args) { SpringApplication.run(ServiceConfigApplication.class, args); }}4. Get configuration rules
Assumptions:
spring.cloud.zookeeper.config.root=xxxx;spring.application.name=abc
zk path:
/xxxx/abc/com/gabo/username
Value:
@value(${com.gabo.username})5. Inspection:
Output at startup: State change: CONNECTED
It means that the connection to zookeeper is successful
Modify the configuration center content, output: Refresh keys changed:
Represents that the value in the project has been modified successfully
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.