pom.xml添加以下引用:node
<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <optional>true</optional> </dependency>
編寫配置類(賦值形式有多種可自行選擇):apache
/** * @author * @date: 2019-01-23 11:35 * @des: 配置加載類 */ public class ZkConfig { private String serverlists; private String zknamespace; private int timeout; private int port; }
註冊服務類:服務器
public class ZkServerUtil { private ZooKeeper zk = null; @Autowired private ZkConfig zkConfig; private void getZkClient() throws Exception { zk = new ZooKeeper(zkConfig.getServerlists(), zkConfig.getTimeout(), new Watcher() { @Override public void process(WatchedEvent watchedEvent) { } }); } /** * TODO 向zookeeper中的/servers下建立子節點 * @throws InterruptedException */ public void connectZK(String serverName) throws Exception { getZkClient(); // 先建立出父節點 if (zk.exists("/"+zkConfig.getZknamespace(), false) == null) { zk.create("/"+zkConfig.getZknamespace(), null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } // 鏈接zk建立znode zk.create("/"+zkConfig.getZknamespace()+ "/"+serverName, (getIP() + ":" + zkConfig.getPort()).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } /** * TODO 獲取對應服務IP地址 * @return */ private String getIP() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) { return inetAddress.getHostAddress(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return null; }
發現服務類:ide
public class ZkClientUtil { private ZooKeeper zk = null; @Autowired private ZkConfig zkConfig; // 獲取zk鏈接 private void getZkClient() throws Exception { // 服務器在需求中並不須要作任何監聽 zk = new ZooKeeper(zkConfig.getServerlists(),zkConfig.getTimeout(), new Watcher() { @Override public void process(WatchedEvent watchedEvent) { } }); } /** * TODO 獲取在線服務器信息 * @param serverName * @return * @throws Exception */ public String getServers(String serverName) throws Exception { getZkClient(); // 從servers父節點下獲取到全部子節點,並註冊監聽 List<String> children = zk.getChildren("/"+zkConfig.getZknamespace(), true); for (String child : children) { if(child.equals(serverName)) { byte[] data = zk.getData("/"+zkConfig.getZknamespace() + "/" + child, false, null); return new String(data); } } return null; } /** * TODO 獲取在線服務器信息列表 * @return * @throws Exception */ public List<String> getServers() throws Exception { getZkClient(); // 從servers父節點下獲取到全部子節點,並註冊監聽 List<String> children = zk.getChildren("/"+zkConfig.getZknamespace(), true); return children; } }