为了保证数据高可用,那么我们采用Zookeeper作为配置中心来保存数据。SpringCloud对Zookeeper的集成官方也有说明:spring_cloud_zookeeper

这里通过实践的方式讲解下使用方式。

1、添加依赖包

<!-- 运维监控 --> <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- Web 应用程序--> <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 提供zookeeper - config --> <dependency>     <groupId>org.springframework.cloud</groupId>     <artifactId>spring-cloud-starter-zookeeper-config</artifactId> </dependency>

配置说明:

org.springframework.cloud#spring-cloud-starter-zookeeper-config 是zookeeper作为配置中心的配置项目。

若是web工程需要添加 org.springframework.boot#spring-boot-starter-web

配置项目 org.springframework.boot#spring-boot-starter-actuator 是用来与zookeeper通信使用的

2、添加配置文件

在bootstrap.properties文件下添加 以下配置

spring.application.name=config-demo spring.profiles.active=dev  #ZooKeeper的连接字符串,如果是集群,逗号分隔节点,格式:ip:port[,ip2:port2,.....] spring.cloud.zookeeper.connect-string = 192.168.0.1:2181 #指定zookeeper目录的根目录 spring.cloud.zookeeper.config.root = config #启用zk的配置 spring.cloud.zookeeper.config.enabled = true spring.cloud.zookeeper.config.profileSeparator = :

配置说明:

请修改 192.168.0.1:2181 为项目中的Zookeeper地址,默认是localhost:2181

根据以上配置,读取zookeeper中的地址为: /config/config-demo:dev

登录zookeeper需要手动创建,或使用zkui来界面维护

3、在Zookeeper中手动创建配置

示例:

[zk: localhost:2181(CONNECTED) 3] create /config/config-demo:dev Created /config/config-demo:dev [zk: localhost:2181(CONNECTED) 4] create /config/config-demo:dev/user.name yuesf Created /config/config-demo:dev/user.name

4、程序中使用

1)创建配置文件

示例: UserProperties.java

package com.example.config;  import org.springframework.boot.context.properties.ConfigurationProperties;  /*  * @auth yuesf  * @data 2019/10/29  */ @ConfigurationProperties(prefix = "user") public class UserProperties {     private String name;