Exemple #1
0
        static void Main(string[] args)
        {
            Sodao.FastSocket.SocketBase.Log.Trace.EnableConsole();
            Sodao.FastSocket.SocketBase.Log.Trace.EnableDiagnostic();

            var client = Sodao.Zookeeper.ZookClientPool.Get("zk1");
            client.Register(new WatcherWrapper(e =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Path);
                Console.WriteLine(e.Type.ToString());
                Console.WriteLine(e.State.ToString());
                Console.ForegroundColor = ConsoleColor.Gray;
            }));

            var watcher = new ChildrenWatcher(client, "/", c =>
            {
                Console.WriteLine(string.Join("-", c));
            });

            Console.ReadLine();
            var sessionNode = new SessionNode(client, "/tempABC", null, IDs.OPEN_ACL_UNSAFE);
            Console.ReadLine();
            sessionNode.Close();

            Console.ReadLine();
        }
Exemple #2
0
        static void Main(string[] args)
        {
            //Sodao.FastSocket.SocketBase.Log.Trace.EnableConsole();
            //Sodao.FastSocket.SocketBase.Log.Trace.EnableDiagnostic();

            var client = Sodao.Zookeeper.ZookClientPool.Get("zk1");
            client.Register(new WatcherAction(e =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Path);
                Console.WriteLine(e.Type.ToString());
                Console.WriteLine(e.State.ToString());
                Console.ForegroundColor = ConsoleColor.Gray;
            }));

            Console.WriteLine("watch zk node /hong2...");
            var watcher = new ChildrenWatcher(client, "/hong2", c =>
            {
                Console.WriteLine(string.Join("-", c));
            });

            Console.WriteLine("create zk session node /hong2/tempABC...");
            var sessionNode = new SessionNode(client, "/hong2/tempABC", null, IDs.OPEN_ACL_UNSAFE);

            Console.WriteLine("create zk node /hong2...");
            NodeCreator.TryCreate(client, new NodeInfo("/hong2", null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent));

            Console.WriteLine("press any key stop thrift client...");
            Console.ReadLine();
            client.Stop();

            Console.WriteLine("press any key start thrift client...");
            Console.ReadLine();
            client.Start();

            Console.WriteLine("press any key dispose zk node(/hong2, /hong2/tempABC)...");
            Console.ReadLine();
            sessionNode.Dispose();
            client.Delete("/hong2");

            Console.WriteLine("press any key exit...");
            Console.ReadLine();
        }
        /// <summary>
        /// start
        /// </summary>
        public void Start()
        {
            if (this._config == null || this._config.Discovery == null ||
                this._config.Discovery.Zookeeper == null || string.IsNullOrEmpty(this._config.Discovery.Zookeeper.ZNode)) return;

            var keeperConfig = this._config.Discovery.Zookeeper;
            var zk = ZookClientPool.Get(keeperConfig.ConfigPath, "zookeeper", keeperConfig.ConfigName);

            //ensure root node...
            var nodes = new NodeInfo[2];
            nodes[0] = new NodeInfo(string.Concat("/", keeperConfig.ZNode), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent);
            nodes[1] = new NodeInfo(string.Concat("/", keeperConfig.ZNode, "/consumers"), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent);
            NodeFactory.TryEnsureCreate(zk, nodes, () =>
            {
                var currProcess = Process.GetCurrentProcess();
                var path = string.Concat("/", keeperConfig.ZNode, "/consumers/", Uri.EscapeDataString(string.Format(
                    "consumer://{0}/{1}?application={2}&category=consumers&check=false&dubbo=2.5.1&interface={1}&methods={6}&owner={3}&pid={4}&revision=0.0.2-SNAPSHOT&side=consumer&timestamp={5}",
                    IPUtility.GetLocalIntranetIP().ToString(),
                    keeperConfig.ZNode,
                    currProcess.ProcessName,
                    string.Empty,
                    currProcess.Id.ToString(),
                    Date.ToMillisecondsSinceEpoch(DateTime.UtcNow).ToString(),
                    this._methods)));
                this._sessionNode = new SessionNode(zk, path, null, IDs.OPEN_ACL_UNSAFE);
            });

            this._watcher = new ChildrenWatcher(zk, string.Concat("/", keeperConfig.ZNode, "/providers"), (names) =>
            {
                //已存在的servers
                var arrExistServers = this._thriftClient.GetAllNodeNames();
                //当前从zk获取到servers
                var arrNowServers = names.Select(s =>
                {
                    var t = Uri.UnescapeDataString(s);
                    t = t.Substring(t.IndexOf(":") + 3);
                    return t.Substring(0, t.IndexOf("/"));
                }).ToArray();

                var set = new HashSet<string>(arrExistServers);
                set.ExceptWith(arrNowServers);
                if (set.Count > 0)
                {
                    foreach (var child in set) this._thriftClient.UnRegisterServerNode(child);
                }

                set = new HashSet<string>(arrNowServers);
                set.ExceptWith(arrExistServers);
                if (set.Count > 0)
                {
                    foreach (var child in set)
                    {
                        int index = child.IndexOf(":");
                        this._thriftClient.RegisterServerNode(child,
                            new IPEndPoint(IPAddress.Parse(child.Substring(0, index)), int.Parse(child.Substring(index + 1))));
                    }
                }
            });
        }
        /// <summary>
        /// stop
        /// </summary>
        public void Stop()
        {
            if (this._sessionNode != null)
            {
                this._sessionNode.Close();
                this._sessionNode = null;
            }

            if (this._watcher != null)
            {
                this._watcher.Stop();
                this._watcher = null;
            }
        }
        /// <summary>
        /// new
        /// </summary>
        /// <param name="serviceType"></param>
        /// <param name="zkConfigPath"></param>
        /// <param name="zkConfigName"></param>
        /// <param name="zNode"></param>
        /// <param name="callback"></param>
        public ZoomkeeperDiscovery(string serviceType,
            string zkConfigPath, string zkConfigName, string zNode,
            Action<IPEndPoint[]> callback)
        {
            if (string.IsNullOrEmpty(serviceType)) throw new ArgumentNullException("serviceType");
            if (string.IsNullOrEmpty(zkConfigPath)) throw new ArgumentNullException("zkConfigPath");
            if (string.IsNullOrEmpty(zkConfigName)) throw new ArgumentNullException("zkConfigName");
            if (string.IsNullOrEmpty(zNode)) throw new ArgumentNullException("zNode");
            if (callback == null) throw new ArgumentNullException("callback");

            this._callback = callback;
            this._zk = ZookClientPool.Get(zkConfigPath, "zookeeper", zkConfigName);
            this.RegisterZNode(new NodeInfo[]
            {
                new NodeInfo(string.Concat("/", zNode), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent),
                new NodeInfo(string.Concat("/", zNode, "/consumers"), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent)
            });
            this._sessionNode = new SessionNode(this._zk,
                string.Concat("/", zNode, "/consumers/", Uri.EscapeDataString(string.Format(
                    @"consumer://{0}/{1}?application={2}&category=consumers&check=false&dubbo=2.5.1&
                    interface={1}&methods={6}&owner={3}&pid={4}&revision=0.0.2-SNAPSHOT&
                    side=consumer&timestamp={5}",
                    IPUtility.GetLocalIntranetIP().ToString(),
                    zNode, Process.GetCurrentProcess().ProcessName, string.Empty, Process.GetCurrentProcess().Id.ToString(),
                    Date.ToMillisecondsSinceEpoch(DateTime.UtcNow).ToString(),
                    string.Join(",", Type.GetType(serviceType).GetInterfaces()[0].GetMethods().Select(c => c.Name).ToArray())))),
                    null, IDs.OPEN_ACL_UNSAFE);

            this._watcher = new ChildrenWatcher(this._zk, string.Concat("/", zNode, "/providers"), arrNodes =>
            {
                this._callback(arrNodes.Select(c =>
                {
                    var objUri = new Uri(Uri.UnescapeDataString(c));
                    return new IPEndPoint(IPAddress.Parse(objUri.Host), objUri.Port);
                }).ToArray());
                //lock (this._lockObj)
                //{
                //    var arrExists = this._thrift.GetAllRegisteredEndPoint().Select(c => c.Key).Distinct().ToArray();
                //    var arrCurr = arrNodes.Select(node =>
                //    {
                //        var strUrl = Uri.UnescapeDataString(node);
                //        strUrl = strUrl.Substring(strUrl.IndexOf(":") + 3);
                //        return strUrl.Substring(0, strUrl.IndexOf("/"));
                //    }).ToArray();

                //    var set = new HashSet<string>(arrExists);
                //    set.ExceptWith(arrCurr);
                //    if (set.Count > 0)
                //    {
                //        foreach (var child in set)
                //            this._thrift.UnRegisterEndPoint(child);
                //    }

                //    set = new HashSet<string>(arrCurr);
                //    set.ExceptWith(arrExists);
                //    if (set.Count > 0)
                //    {
                //        foreach (var child in set)
                //        {
                //            var i = child.IndexOf(":");
                //            var endpoint = new IPEndPoint(IPAddress.Parse(child.Substring(0, i)), int.Parse(child.Substring(i + 1)));
                //            this._thrift.TryRegisterEndPoint(child, new EndPoint[] { endpoint });
                //        }
                //    }
                //}
            });
        }