zookeeper注册与发现

pom.xml添加如下引用:

  <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <optional>true</optional>
        </dependency>

编写配置类(赋值形式有多种可自行选择):

/**
 * @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;
    }

 

发现服务类:

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;
    }
}

 

posted @ 2019-03-05 14:16  瑾谦  阅读(595)  评论(0编辑  收藏  举报