zookeeper作为配置中心
业务需求:zookeeper作为配置中心,对配置的信息进行监听,当配置内容发生改变时可以得到最新的配置信息
创建配置中心所需节点
代码
public class MyConfigCenter implements Watcher {
//计数器对象
CountDownLatch CountDownLatch=new CountDownLatch(1);
String IP="192.168.164.134:2181";
ZooKeeper zooKeeper;
//设置配置文件内容
String url,userName,password;
@Override
public void process(WatchedEvent event) {
if(event.getType()==Event.EventType.None){
if(event.getState()==Event.KeeperState.SyncConnected){
System.out.println("连接创建成功");
//唤醒线程
CountDownLatch.countDown();
}
if(event.getState()==Event.KeeperState.Disconnected){
System.out.println("断开连接");
}
if(event.getState()==Event.KeeperState.Expired){
System.out.println("会话超时");
}
if(event.getState()==Event.KeeperState.AuthFailed){
System.out.println("认证失败");
}
} else if(event.getType()==Event.EventType.NodeDataChanged){
//当配置信息发生变化时
initValue();
}
}
//构造对象时就得到初始配置信息
public MyConfigCenter() {
initValue();
}
//得到初始配置信息
public void initValue(){
try{
zooKeeper= new ZooKeeper(IP,5000,this);
//阻塞线程直到连接成功
CountDownLatch.await();
//读取配置
this.url=new String(zooKeeper.getData("/config/url", true, null));
this.userName=new String(zooKeeper.getData("/config/username", true, null));
this.password=new String(zooKeeper.getData("/config/password", true, null));
}catch (Exception e){
e.printStackTrace();
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
测试
//模拟工具类获取配置信息
public static void main(String[] args) {
try{
MyConfigCenter myConfigCenter = new MyConfigCenter();
while (true){
Thread.sleep(5000);
System.out.println(myConfigCenter.getUrl());
System.out.println(myConfigCenter.getUserName());
System.out.println(myConfigCenter.getPassword());
}
}catch (Exception e){
e.printStackTrace();
}
}