利用Zookeeper進行服務發現主要涉及以下幾個步驟:
服務注冊:
/services/{服務名稱}/{服務實例的唯一標識}
。保持心跳:
服務發現:
具體實現:
import org.apache.zookeeper.*;
public class ServiceProvider {
private static final String ZOOKEEPER_ADDRESS = "localhost:2181";
private static final String SERVICE_PATH = "/services/my-service";
public static void main(String[] args) throws Exception {
ZooKeeper zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, 3000, event -> {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("Connected to Zookeeper");
}
});
// 注冊服務
String serviceInstance = SERVICE_PATH + "/instance1";
zooKeeper.create(serviceInstance, "127.0.0.1:8080".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// 保持服務存活狀態
while (true) {
Thread.sleep(1000);
}
}
}
public class ServiceConsumer {
private static final String ZOOKEEPER_ADDRESS = "localhost:2181";
private static final String SERVICE_PATH = "/services/my-service";
public static void main(String[] args) throws Exception {
ZooKeeper zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, 3000, null);
// 監聽節點變化
List<String> serviceInstances = zooKeeper.getChildren(SERVICE_PATH, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeChildrenChanged) {
try {
List<String> updatedInstances = zooKeeper.getChildren(SERVICE_PATH, this);
System.out.println("Updated service instances: " + updatedInstances);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
// 輸出初始的服務實例
System.out.println("Initial service instances: " + serviceInstances);
// 保持程序運行
while (true) {
Thread.sleep(1000);
}
}
}
通過以上步驟和示例代碼,可以利用Zookeeper實現基本的服務注冊與發現功能。