package com.lightinit.hsdatashow.common; import com.lightinit.hsdatashow.json.pojo.ServerEntity; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.springframework.util.StringUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Created by Mr.Yao on 2017/10/10. */ public class BaseRemoteClient implements Watcher{ private final Random random=new Random(); List list = new ArrayList(); private ZooKeeper zooKeeper=null; protected BaseRemoteClient(String node, String service){ //RegisterServerList(node,service); } protected void RegisterServerList(String node, String service) { try { if (zooKeeper == null) { ThriftServerConfig config = new ThriftServerConfig(); zooKeeper = new ZooKeeper(config.getHost() + ":" + config.getPort(), 30000, this); if (zooKeeper.exists("/thrift", false) != null) { if (zooKeeper.exists(String.format("/thrift/%s", node), false) != null) { if (zooKeeper.exists(String.format("/thrift/%s/%s", node, service), true) != null) { list = zooKeeper.getChildren(String.format("/thrift/%s/%s", node, service), true); } } } } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } } public ServerEntity SelectServer(){ ServerEntity item=new ServerEntity(); if(list.size()<=0){ item.setServerIp("127.0.0.1"); item.setServerPort(9876); }else{ String serverIp=list.get(random.nextInt(list.size())); if (StringUtils.isEmpty(serverIp)){ item.setServerIp("127.0.0.1"); item.setServerPort(9876); }else{ String []infos= serverIp.split(":"); if(infos.length==2) { item.setServerIp(infos[0]); item.setServerPort(Integer.valueOf(infos[1])); }else{ item.setServerIp("127.0.0.1"); item.setServerPort(9876); } } } return item; } @Override public void process(WatchedEvent watchedEvent) { } }