思路参考Thrift 客户端 C#
http://blog.csdn.net/gzy11/article/details/78503015
http://blog.csdn.net/gzy11/article/details/78502492
import org.apache.commons.lang3.StringUtils; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TSocket; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.io.IOException; import java.util.List; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; /** * thrift 客户端封装 * */ public class Client extends Object { /** * 多线程锁 */ private static final Object look = new Object(); /** * 客户端池-根据不同业务自动选择对应业务客户端 */ private static ConcurrentHashMap<String, Client> clientPool = new ConcurrentHashMap<String, Client>(); /** * 使用一个zookeeper客户端 */ private static ZooKeeper zookeeper = null; /** * zookeeper链接字符串 */ public String zookeeperConnectString = "192.168.145.3:2281,192.168.145.4:2281,192.168.145.7:228";//注意替换为读取配置 /** * zookeeper-所有监视节点 */ public List<String> nodeChildren = null; /** * 客户端-TBinaryProtocol/[c# TBufferedTransport] */ ConcurrentHashMap<String, TProtocol> tProtocol = new ConcurrentHashMap<String, TProtocol>(); /** * zookeeper注册及监视节点 */ private String path = "/test/servicecenter-dev/services/%s/providers";//注意替换为读取配置 /** * zookeeper注册唯一标识 */ private String rpcServicenamespace = null; /** * 轮询负载计数器 */ private int countLoadbalance = 0; /** * 构造函数 * * @param rpcServicenamespace */ public Client(String rpcServicenamespace) { this.rpcServicenamespace = rpcServicenamespace; this.path = String.format(this.path, this.rpcServicenamespace); System.out.println("初始化:" + this.path); } /** * 获取一个唯一实例 * * @param key * @param concurrentHashMap * @param t * @param <T> * @return */ public static <T> T getSingleInstance(String key, ConcurrentHashMap<String, T> concurrentHashMap, T t) { if (!concurrentHashMap.containsKey(key)) { synchronized (look) { if (!concurrentHashMap.containsKey(key)) { //TProtocol protocol= t instanceof TBinaryProtocol ? ((TBinaryProtocol) t) : null; //if (protocol != null){ concurrentHashMap.putIfAbsent(key, t); //} } } } return concurrentHashMap.get(key); } /** * @param rpcServicenamespace * @return Client */ public static Client getSingleInstance(String rpcServicenamespace) { return getSingleInstance(rpcServicenamespace, clientPool, new Client(rpcServicenamespace)); } /** * 初始化 */ public void init() { createZookeeperClient(); } /** * 创建一个zookeeper客户端 * * @return */ public ZooKeeper createZookeeperClient() { if (zookeeper == null) { synchronized (look) { if (zookeeper == null) { int errorCount = 0; while (true) { if (createZookeeper() != null) { break; } else { long millis = 1000; errorCount = threadSleep(millis, errorCount); } if (errorCount >= 60) {//错误大于60次就退出! System.out.println("zookeeper创建错误大于60次了!"); break; } } int count = 0; while (true) { if (zookeeper.getState() == ZooKeeper.States.CONNECTED) { System.out.println("zookeeper连接成功!"); break; } long millis = 1000; count = threadSleep(millis, count); if (count >= 90) { System.out.println("zookeeper至少超过1分30秒,没有连接成功!"); break; } } getChildrenWatcher(); } } } return zookeeper; } /** * 创建一个zookeeper客户端 * * @return */ private ZooKeeper createZookeeper() { String connectstring = this.zookeeperConnectString;// "192.168.145.3:2281,192.168.145.4:2281,192.168.145.7:228";// GetConfig()["ZookeeperConnectString"];//["YinXin.BaoXian.RegionCityRPC"]; int sessionTimeout = 60; ZookeeperWatcher watcher = new ZookeeperWatcher(this.rpcServicenamespace); try { zookeeper = new ZooKeeper(zookeeperConnectString, sessionTimeout, watcher); } catch (IOException e) { System.out.print(e); } finally { return zookeeper; } } /** * 线程休眠 * * @param millis * @param count * @return */ private int threadSleep(long millis, int count) { try { //long millis = 1000; Thread.sleep(millis); count++; } catch (InterruptedException e) { System.out.println("线程休眠异常,够扯淡的了!"); count++; } finally { return count; } } /** * 客户端监视-想监视的节点 */ public void getChildrenWatcher() { List<String> nodeChildren = null; boolean isError = false; System.out.println("监视:" + path); try { nodeChildren = zookeeper.getChildren(path, true); } catch (Exception e) { System.out.println(e); isError = true; } if (!isError) { synchronized (nodeChildren) { this.nodeChildren = nodeChildren; } } if (nodeChildren == null) { return; } for (String item : nodeChildren) { try { zookeeper.exists(path + "/" + item, true); } catch (InterruptedException e) { System.out.println("创建监视异常!" + e); } catch (KeeperException e) { System.out.println("创建监视异常!" + e); } } } /** * 随机 * * @return */ public String random() { List<String> nodeChildren = null; if (this.nodeChildren != null) { synchronized (this.nodeChildren) { nodeChildren = this.nodeChildren; } Random random = new Random(); int count = nodeChildren.size(); if (count == 0) { System.out.println("随机--无节点!"); return "false"; } int index = random.nextInt(count - 1); return nodeChildren.get(index); } System.out.println("随机--无节点!"); return "false"; } /** * 简单轮询 * * @return */ public String loadbalance() { int index = 0; List<String> nodeChildren = null; if (this.nodeChildren != null) { synchronized (this.nodeChildren) { nodeChildren = this.nodeChildren; countLoadbalance++; countLoadbalance = countLoadbalance > this.nodeChildren.size() ? 1 : countLoadbalance; index = countLoadbalance; } } if (index - 1 >= 0 && nodeChildren != null && nodeChildren.size() != 0) { return nodeChildren.get(index - 1); } else { System.out.println("轮询--无节点"); return "轮询无节点"; } } /** * 随机负载 * @param servers * @return */ public TProtocol getTSocket(String servers) { if (StringUtils.isWhitespace(servers)) { return null; } //string servers = thriftClient.Random();//随机负载 String[] list = servers.split(":"); if (list.length == 2) { //var tbufferedTransport = GetSingleInstance<TBufferedTransport>(_tBufferedTransportPool, servers, new TBufferedTransport(new TSocket(list[0], int.Parse(list[1])))); /*int port =Integer.parseInt(list[1]); TTransport tTransport = new TSocket(list[0], Integer.parseInt(list[1])); TProtocol tProtocol = new TBinaryProtocol(tTransport);*/ return getSingleInstance(servers, this.tProtocol, new TBinaryProtocol(new TSocket(list[0], Integer.parseInt(list[1])))); } else { return null; } } /** * 释放资源 * * @throws java.lang.Throwable */ protected void finalize() throws java.lang.Throwable { super.finalize(); System.out.println("被释放!"); } }
import org.apache.commons.lang3.StringUtils; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; /** * zookeeper的Watcher监视实现 * */ public class ZookeeperWatcher implements Watcher { /** * thrift封装的客户端 */ private Client client; /** * 构造函数 * * @param rpcServicenamespace */ public ZookeeperWatcher(String rpcServicenamespace) { client = Client.getSingleInstance(rpcServicenamespace); } /** * 实现监视节点 * * @param event */ public void process(WatchedEvent event) { switch (event.getType()) { case None: System.out.println("None"); break; case NodeCreated: System.out.println("NodeCreated"); break; case NodeDeleted: System.out.println("NodeDeleted"); //client.getChildrenWatcher();//监测节点 if (!StringUtils.isWhitespace(event.getPath())) { String eventPath = event.getPath(); String path = eventPath.substring(0, eventPath.lastIndexOf("/")); String name = eventPath.substring(eventPath.lastIndexOf("/") + 1); if (client.tProtocol.containsKey(name)) { synchronized (client.tProtocol) { if (client.tProtocol.containsKey(name)) { client.tProtocol.get(name).getTransport().close(); client.tProtocol.remove(name); } } } } break; case NodeDataChanged: System.out.println("NodeDataChanged"); break; case NodeChildrenChanged: System.out.println("NodeChildrenChanged"); client.getChildrenWatcher();//监测节点 //Console.Write(" EventType.NodeChildrenChanged"); break; /* case DataWatchRemoved: System.out.println("DataWatchRemoved"); break; case ChildWatchRemoved: System.out.println("ChildWatchRemoved"); break; */ } } }
占坑待续.......