基於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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM