基于Zookeeper的配置中心
上一篇 spring boot集成zookeeper注册中心
现在看下基于基于Zookeeper的配置中心实现
在Zookeeper建立一个根节点,比如/config,代表某个配置文件
让所有使用到该配置信息的应用机器集成Zookeeper并监控/config的状态
一旦配置信息也就是子节点发生变化,每台应用机器就会收到ZK的通知,然后从ZK中获取新的配置信息应用到系统中
1.依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-config</artifactId> </dependency> </dependencies>
2.创建配置文件
使用@ConfigurationProperties 特性,标记类为配置文件
package com.xyz.provider;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@ConfigurationProperties("order")
@RefreshScope
@Data
@Component
public class OrderProperties {
private Integer discount = 100;
}
3.控制器
package com.xyz.provider.controller;
import com.xyz.provider.OrderProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class demoController {
@Autowired
private OrderProperties orderProperties;
@RequestMapping("/search")
public Integer searchDiscount() {
return orderProperties.getDiscount();
}
}
4.启用配置
server.port=8010 management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always spring.profiles.active=dev spring.application.name=config-demo spring.cloud.zookeeper.connect-string=192.168.99.100:2181 spring.cloud.zookeeper.config.root=config spring.cloud.zookeeper.config.enabled=true spring.cloud.zookeeper.config.watcher.enabled=true spring.cloud.zookeeper.config.profileSeparator=:
注:
配置文件bootstrap.yml / bootstrap.properties中加入zookeeper连接信息
写到application.properties会报错
Opening socket connection to server localhost/0:0:0:0:0:0:0:1:2181. Will not attempt to authenticate using SASL
因为配置的组合顺序为
应用名-profile.properties 应用名.properties application-profile.properties application.properties
6.在Zookeeper中手动创建配置
根据上面的配置
create /config create /config/config-demo create /config/config-demo:dev create /config/config-demo:dev/order.discount 60
获取值
get /config/config-demo:dev/order.discount
启动项目
测试 GET http://localhost:8010/search
获取的为60
修改
set /config/config-demo:dev/order.discount 70
不用重启直接获取的为70