BaseRemoteClient.java 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package com.lightinit.hsdatashow.common;
  2. import com.lightinit.hsdatashow.json.pojo.ServerEntity;
  3. import org.apache.zookeeper.KeeperException;
  4. import org.apache.zookeeper.WatchedEvent;
  5. import org.apache.zookeeper.Watcher;
  6. import org.apache.zookeeper.ZooKeeper;
  7. import org.springframework.util.StringUtils;
  8. import java.io.IOException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.Random;
  12. /**
  13. * Created by Mr.Yao on 2017/10/10.
  14. */
  15. public class BaseRemoteClient implements Watcher{
  16. private final Random random=new Random();
  17. List<String> list = new ArrayList<String>();
  18. private ZooKeeper zooKeeper=null;
  19. protected BaseRemoteClient(String node, String service){
  20. //RegisterServerList(node,service);
  21. }
  22. protected void RegisterServerList(String node, String service) {
  23. try {
  24. if (zooKeeper == null) {
  25. ThriftServerConfig config = new ThriftServerConfig();
  26. zooKeeper = new ZooKeeper(config.getHost() + ":" + config.getPort(), 30000, this);
  27. if (zooKeeper.exists("/thrift", false) != null) {
  28. if (zooKeeper.exists(String.format("/thrift/%s", node), false) != null) {
  29. if (zooKeeper.exists(String.format("/thrift/%s/%s", node, service), true) != null) {
  30. list = zooKeeper.getChildren(String.format("/thrift/%s/%s", node, service), true);
  31. }
  32. }
  33. }
  34. }
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. } catch (InterruptedException e) {
  38. e.printStackTrace();
  39. } catch (KeeperException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. public ServerEntity SelectServer(){
  44. ServerEntity item=new ServerEntity();
  45. if(list.size()<=0){
  46. item.setServerIp("127.0.0.1");
  47. item.setServerPort(9876);
  48. }else{
  49. String serverIp=list.get(random.nextInt(list.size()));
  50. if (StringUtils.isEmpty(serverIp)){
  51. item.setServerIp("127.0.0.1");
  52. item.setServerPort(9876);
  53. }else{
  54. String []infos= serverIp.split(":");
  55. if(infos.length==2) {
  56. item.setServerIp(infos[0]);
  57. item.setServerPort(Integer.valueOf(infos[1]));
  58. }else{
  59. item.setServerIp("127.0.0.1");
  60. item.setServerPort(9876);
  61. }
  62. }
  63. }
  64. return item;
  65. }
  66. @Override
  67. public void process(WatchedEvent watchedEvent) {
  68. }
  69. }