zk - zookeeper實現配置中心
阿新 • • 發佈:2020-12-29
世界上並沒有完美的程式,但是我們並不因此而沮喪,因為寫程式就是一個不斷追求完美的過程。
使用zk實現配置中心,只要抓住兩點:
- znode儲存配置資訊
- watch監聽配置資訊的變化
下面是實現過程:
public class ConfigCenter {
@Test
public void test() {
put();
get();
}
/**
* 配置資訊的上傳
*/
private void put() {
try {
String path = "/application.yml";
File file = new File(this.getClass().getResource(path).getFile());
FileInputStream in = new FileInputStream(file);
byte[] bytes = new byte[in.available()];
in.read(bytes);
in.close();
String connect = "127.0.0.1:2181";
ZkClient client = new ZkClient(connect);
client.setZkSerializer(new BytesPushThroughSerializer());
String configPath = "/config1";
if (client.exists(configPath)) {
client.writeData(configPath, bytes);
} else {
client.createPersistent(configPath, bytes);
}
client.close();
} catch (Exception e) {e.printStackTrace();}
}
/**
* 配置資訊的獲取
*/
public void get() {
String connect = "127.0.0.1:2181";
ZkClient client = new ZkClient(connect);
client.setZkSerializer(new BytesPushThroughSerializer());
String configPath = "/config1";
// 啟動時首先讀取配置資訊
byte[] bs = client.readData(configPath);
System.out.println("config data : " + new String(bs));
// 監聽配置資訊的變化
client.subscribeDataChanges(configPath, new IZkDataListener() {
@Override
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("data change path : " + s);
System.out.println("data change : " + new String((byte[]) o));
}
@Override
public void handleDataDeleted(String s) throws Exception {
System.out.println("data delete path : " + s);
}
});
try {
Thread.sleep(30000);
} catch (Exception e) {e.printStackTrace();}
}
}
如上,每個配置檔案對應一個znode,就可以實現配置的集中處理,即配置中心。
當然如果實際使用還需要進行配置資訊的解析或者寫入等操作,在spring cloud中獲取實時修改的配置資訊,需要@RefreshScope註解的配合。當然也可以自己重新整理配置,如通過applicationContext.refresh()。後續需要自己根據實際情況來實現了。