コード例 #1
1
ファイル: Program.cs プロジェクト: Indifer/Test
        static void Main(string[] args)
        {
             //创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法 
            using (ZooKeeper zk = new ZooKeeper("121.199.25.195:2181", new TimeSpan(0, 0, 0, 50000), new Watcher()))
            {
                var stat = zk.Exists("/root", true);

                //创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失) 
                zk.Create("/root", "mydata".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                //在root下面创建一个childone znode,数据为childone,不进行ACL权限控制,节点为永久性的 
                zk.Create("/root/childone", "childone".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                //取得/root节点下的子节点名称,返回List<String> 
                zk.GetChildren("/root", true);
                //取得/root/childone节点下的数据,返回byte[] 
                zk.GetData("/root/childone", true, null);

                //修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉
                zk.SetData("/root/childone", "childonemodify".GetBytes(), -1);
                //删除/root/childone这个节点,第二个参数为版本,-1的话直接删除,无视版本 
                zk.Delete("/root/childone", -1);
            }


        }
コード例 #2
0
        public T GetData <T>(string nodePath, IWatcher watcher) where T : new()
        {
            T data = default(T);

            if (isDisposed)
            {
                return(data);
            }
            int tries = retries;

            while ((tries--) > 0)
            {
                try
                {
                    byte[] readData = zk.GetData(nodePath, watcher, null);
                    data = ZNodesDataStructures.deserialize <T>(readData);
                    break;
                }
                catch (Exception ex)
                {
                    if (tries == 0)
                    {
                        Console.WriteLine("GetData exception after #" + retries + " retries :\n" + ex.Message);
                        Console.WriteLine("Last retry, throwing exception");
                        throw ex;
                    }
                }
            }
            return(data);
        }
コード例 #3
0
        public void GetZookeeperNodeStatAndData()
        {
            if (this.SelectedZookeeperTreeNodeModel != null)
            {
                ListViewDataContext.Clear();
                Data = null;

                try
                {
                    Stat stat = GetZookeeperNodeStat(this.SelectedZookeeperTreeNodeModel.QueryPath);
                    if (stat != null)
                    {
                        this.ChangeListView(stat);
                        Data = _zk.GetData(this.SelectedZookeeperTreeNodeModel.QueryPath, false, stat);
                        this.SelectedZookeeperTreeNodeModel.Stat = stat;
                    }
                    else
                    {
                        this.AddLog(LogType.Error, string.Concat("this node had removed:", this.SelectedZookeeperTreeNodeModel.QueryPath));
                    }
                }
                catch (Exception ex)
                {
                    this.AddLog(LogType.Fatal, ex.Message);
                }
            }
        }
コード例 #4
0
        public void testSequentialNodeData()
        {
            string queue_handle = "/queue" + Guid.NewGuid();

            using (ZooKeeper zk = CreateClient())
            {
                zk.Create(queue_handle, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                zk.Create(queue_handle + "/element", "0".GetBytes(), Ids.OPEN_ACL_UNSAFE,
                          CreateMode.PersistentSequential);
                zk.Create(queue_handle + "/element", "1".GetBytes(), Ids.OPEN_ACL_UNSAFE,
                          CreateMode.PersistentSequential);
                var children = zk.GetChildren(queue_handle, true);
                Assert.Equal(children.Count(), 2);
                string child1        = children.ElementAt(0);
                string child2        = children.ElementAt(1);
                int    compareResult = child1.CompareTo(child2);
                Assert.Equal(compareResult, 0);
                if (compareResult < 0)
                {
                }
                else
                {
                    string temp = child1;
                    child1 = child2;
                    child2 = temp;
                }
                string child1data = Encoding.UTF8.GetString(zk.GetData(queue_handle + "/" + child1, false, null));
                string child2data = Encoding.UTF8.GetString(zk.GetData(queue_handle + "/" + child2, false, null));
                Assert.Equal(child1data, "0");
                Assert.Equal(child2data, "1");
            }
        }
コード例 #5
0
        /// <summary>
        /// Processes the specified watched event.
        /// </summary>
        /// <param name="watchedEvent">The watched event.</param>
        public void Process(WatchedEvent watchedEvent)
        {
            try
            {
                byte[] _nodeData = null;
                switch (watchedEvent.Type)
                {
                case EventType.None:
                    break;

                case EventType.NodeCreated:
                    ZooKeeper.GetChildren(watchedEvent.Path, this, null);
                    _nodeData = ZooKeeper.GetData(watchedEvent.Path, this, null);

                    if (OnNodeChangeEvent != null)
                    {
                        OnNodeChangeEvent(watchedEvent, _nodeData);
                    }
                    break;

                case EventType.NodeDeleted:

                    ZooKeeper.Exists(watchedEvent.Path, this);

                    if (OnNodeChangeEvent != null)
                    {
                        OnNodeChangeEvent(watchedEvent, null);
                    }
                    break;

                case EventType.NodeChildrenChanged:
                    var _chlidrenNode = ZooKeeper.GetChildren(watchedEvent.Path, this, null);
                    if (OnNodeChildrenChangeEvent != null)
                    {
                        OnNodeChildrenChangeEvent(watchedEvent, _chlidrenNode.ToArray());
                    }
                    break;

                default:

                    _nodeData = ZooKeeper.GetData(watchedEvent.Path, this, null);
                    if (OnNodeChangeEvent != null)
                    {
                        OnNodeChangeEvent(watchedEvent, _nodeData);
                    }
                    break;
                }
            }
            catch (NoNodeException ex)
            {
                if (OnNodeExceptionEvent != null)
                {
                    OnNodeExceptionEvent(ex, Path);
                }
            }
        }
コード例 #6
0
ファイル: Client.cs プロジェクト: mallickhruday/MyDemos
        public void test()
        {
            var stat = zk.Exists("/tasks", this);

            if (stat != null)
            {
                var data = zk.GetData("/tasks", true, stat);
                zk.GetChildren("/tasks", true);
            }
        }
コード例 #7
0
ファイル: ZookeeperService.cs プロジェクト: kavindu23110/CDN
        public List <KeyValuePair <long, string> > GetClusterNodes(string ClusterName)
        {
            List <KeyValuePair <long, string> > kv = new List <KeyValuePair <long, string> >();
            var nodes = (List <string>)zk.GetChildren("/" + ClusterName, true);

            foreach (var item in nodes)
            {
                var byteArray = zk.GetData($"/{ BOD.NodeDetails.ClusterName}/{item}", true, null);

                kv.Add(new KeyValuePair <long, string>(ByteToLong(byteArray), item.Substring(0, item.IndexOf("-"))));
            }
            return(kv);
        }
コード例 #8
0
            public void Process(WatchedEvent @event)
            {
                try
                {
                    if (@event.Type == EventType.None)
                    {
                        return;
                    }

                    if (@event.Type == EventType.NodeCreated)
                    {
                        _zk.GetChildren(@event.Path, this, null);
                        var nodeData = _zk.GetData(@event.Path, this, null);

                        if (_nodeChangecallback != null)
                        {
                            _nodeChangecallback(@event, nodeData);
                        }
                    }
                    else if (@event.Type == EventType.NodeDeleted)
                    {
                        _zk.Exists(@event.Path, this);

                        if (_nodeChangecallback != null)
                        {
                            _nodeChangecallback(@event, null);
                        }
                    }
                    else if (@event.Type == EventType.NodeChildrenChanged)
                    {
                        var chlidrenNode = _zk.GetChildren(@event.Path, this, null);
                        if (_nodeChildrenChangecallback != null)
                        {
                            _nodeChildrenChangecallback(@event, chlidrenNode.ToArray());
                        }
                    }
                    else
                    {
                        var nodeData = _zk.GetData(@event.Path, this, null);
                        if (_nodeChangecallback != null)
                        {
                            _nodeChangecallback(@event, nodeData);
                        }
                    }
                }
                catch (KeeperException.NoNodeException e)
                {
                    _zk.Exists(@event.Path, this);
                    Console.WriteLine("ERROR");
                }
            }
コード例 #9
0
        static void Main(string[] args)
        {
            // 创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法
            using (var zk = new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 0, 50000), new Watcher()))
            {
                var stat = zk.Exists("/root", true);

                // 创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失)
                // zk.Create("/root", "mydata".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                // 在root下面创建一个childone znode,数据为childone,不进行ACL权限控制,节点为永久性的
                zk.Create("/root/childone", "childone".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                // 取得/root节点下的子节点名称,返回List<String>
                zk.GetChildren("/root", true);

                // 取得/root/childone节点下的数据,返回byte[]
                zk.GetData("/root/childone", true, null);

                // 修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉
                zk.SetData("/root/childone", "childonemodify".GetBytes(), -1);

                // 删除/root/childone这个节点,第二个参数为版本,-1的话直接删除,无视版本
                zk.Delete("/root/childone", -1);
            }

            Console.ReadKey();
        }
コード例 #10
0
        private string[] GetNodeIp(string serverIp)
        {
            var b = zookeeper.GetData("/config/" + serverIp + "/ip.txt", false, null);
            var r = System.Text.Encoding.UTF8.GetString(b);

            return(r.Split('\n'));
        }
コード例 #11
0
ファイル: ConfigManager.cs プロジェクト: pigzhuzhu55/DisConf
        private void _itemWatcher_NodeChanged(string obj)
        {
            this._handler.Execute(() =>
            {
                using (MaintainWatcher mk = new MaintainWatcher(config.Host, 1000))
                {
                    ZooKeeper zk     = mk.ZooKeeper;
                    Stat stat        = new Stat();
                    var tmpdata      = zk.GetData(obj, false, stat);
                    string tmpString = System.Text.Encoding.UTF8.GetString(tmpdata);

                    ZNode znode = Deserialize(tmpString);
                    if (znode == null)
                    {
                        return;
                    }
                    znode.Version = stat.Version;

                    //获取本地的版本号,如果比服务器的低,则更新
                    string file  = Path.Combine(ClientPath, obj.TrimStart('/') + ".txt");
                    string text  = FileHelper.ReadFile(file);
                    ZNode zLocal = Deserialize(text);

                    if (zLocal == null || zLocal.Version < znode.Version)
                    {
                        FileHelper.WriteFile(file, znode.ToString());
                        LogHelper.WriteCustom($"更新节点:{$"{obj}"},值:{JsonHelper.ToNewtonJsonString(znode)}", "zookeeper\\", false);
                    }
                    //刷新内存值
                    this._itemWatcher.RefreshConfigValue(obj, znode.Value);
                }
            }, string.Format("Some thing is wrong with item '{0}'", obj));
        }
コード例 #12
0
        //static List<Org.Apache.Zookeeper.Data.ACL> CreateAllAccessACLList()
        //{
        //    var list = new List<Org.Apache.Zookeeper.Data.ACL>();

        //    var ZKid = new Org.Apache.Zookeeper.Data.ZKId("world", "anyone");
        //    var acl = new Org.Apache.Zookeeper.Data.ACL(ZooKeeperNet.Perms.ALL, ZKid);

        //    list.Add(acl);

        //    return list;
        //}

        static void Main(string[] args)
        {
            string path = "/zk-book";

            zk = new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 5), new ZooKeeper_SetData_API_Sync_Usage());
            manualWaitHandler.WaitOne();

            if (zk.Exists(path, false) == null)
            {
                zk.Create(path, "123".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral);
            }
            Console.WriteLine(zk.GetData(path, true, null));

            var stat = zk.SetData(path, "456".GetBytes(), -1);

            Console.WriteLine("{0}, {1}, {2}", stat.Czxid, stat.Mzxid, stat.Version);

            var stat2 = zk.SetData(path, "456".GetBytes(), stat.Version);

            Console.WriteLine("{0}, {1}, {2}", stat2.Czxid, stat2.Mzxid, stat2.Version);

            try
            {
                zk.SetData(path, "456".GetBytes(), stat.Version);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
            }

            Console.ReadLine();
        }
コード例 #13
0
ファイル: MaxTxId.cs プロジェクト: orf53975/hadoop.net
 /// <exception cref="System.IO.IOException"/>
 internal virtual long Get()
 {
     lock (this)
     {
         try
         {
             currentStat = zkc.Exists(path, false);
             if (currentStat == null)
             {
                 return(0);
             }
             else
             {
                 byte[] bytes = zkc.GetData(path, false, currentStat);
                 BKJournalProtos.MaxTxIdProto.Builder builder = BKJournalProtos.MaxTxIdProto.NewBuilder
                                                                    ();
                 TextFormat.Merge(new string(bytes, Charsets.Utf8), builder);
                 if (!builder.IsInitialized())
                 {
                     throw new IOException("Invalid/Incomplete data in znode");
                 }
                 return(((BKJournalProtos.MaxTxIdProto)builder.Build()).GetTxId());
             }
         }
         catch (KeeperException e)
         {
             throw new IOException("Error reading the max tx id from zk", e);
         }
         catch (Exception ie)
         {
             throw new IOException("Interrupted while reading thr max tx id", ie);
         }
     }
 }
コード例 #14
0
        public bool GetNodeValue(string nodePath, ref string nodeValue, ref string message)
        {
            nodeValue = string.Empty;

            try
            {
                using (ZooKeeper zk = new ZooKeeper(AppSettingsHelper.ZKServer, TimeSpan.FromSeconds(AppSettingsHelper.ZKSessionTimeOut), null))
                {
                    ZooKeeper.WaitUntilConnected(zk);

                    Stat stat = zk.Exists(nodePath, true);
                    if (stat == null)
                    {
                        message = string.Format("该节点【{0}】已被别人删除。", nodePath);
                        return(false);
                    }

                    byte[] _nodeValue = zk.GetData(nodePath, false, stat);
                    if (_nodeValue != null && _nodeValue.Length > 0)
                    {
                        nodeValue = Encoding.UTF8.GetString(_nodeValue);
                    }
                }
            }
            catch (Exception ex)
            {
                message = string.Format("JinRi.Fx.Manage:{0}GetNodeValue()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                log.Error(message);
                message = string.Format("GetNodeValue()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                return(false);
            }

            return(true);
        }
コード例 #15
0
        public void Subscribe()
        {
            var w = new watcher();
            var zk = new ZooKeeper("", TimeSpan.FromSeconds(1), w);
            w.WaitUntilConnected(1);

            zk.GetData("", w, new Stat());
        }
コード例 #16
0
        /// <summary>
        ///     Fetches data from a given path in ZooKeeper
        /// </summary>
        /// <param name="path">
        ///     The given path.
        /// </param>
        /// <param name="stats">
        ///     The statistics.
        /// </param>
        /// <param name="watch">
        ///     Indicates whether should reinstall watcher in ZooKeeper.
        /// </param>
        /// <returns>
        ///     Data
        /// </returns>
        public byte[] ReadData(string path, Stat stats, bool watch)
        {
            Guard.NotNullNorEmpty(path, "path");

            EnsuresNotDisposedAndNotNull();
            var nodedata = _zkclient.GetData(path, watch, stats);

            return(nodedata);
        }
コード例 #17
0
ファイル: ZkACL.cs プロジェクト: hongying1991/ZooKeeperSample
        public static void GetACL()
        {
            Stat stat = new Stat();
            var  data = zk.GetACL("/test", stat); // 第二个参数不允许为空,为空时会报错

            // ip 和 world 不需要也不能添加 AddAuthInfo
            zk.AddAuthInfo("digest", "user1:12345".GetBytes());
            var data1 = System.Text.Encoding.Default.GetString(zk.GetData("/test", false, stat));
        }
コード例 #18
0
        public void Subscribe()
        {
            var w  = new watcher();
            var zk = new ZooKeeper("", TimeSpan.FromSeconds(1), w);

            w.WaitUntilConnected(1);

            zk.GetData("", w, new Stat());
        }
コード例 #19
0
        // GETTERS

        public byte[] GetNodeDataRaw(string path, bool watch)
        {
            byte[] result = null;
            if (!string.IsNullOrEmpty(path))
            {
                try
                {
                    result = zk.GetData(path, watch, zk.Exists(path, false));
                }
                catch (KeeperException kex)
                {
                    // always log your exceptions!
                    //Logger.Error("ZooKeeperClient", "Exception occurred at getNodeDataRaw", kex);
                    this.Close();
                    return(null);
                }
            }
            return(result);
        }
コード例 #20
0
        public string getData(string path)
        {
            List <string> list = new List <string>();

            zkWatchCreator.Exists(path, true);

            byte[] bs = zkWatchCreator.GetData(path, false, null);

            return(Encoding.UTF8.GetString(bs));
        }
コード例 #21
0
        public string DataGet(string Path)
        {
            var stat = new Stat();

            var byteArray = zk.GetData(Path, false, stat);

            string result = System.Text.Encoding.UTF8.GetString(byteArray);

            return(result);
        }
コード例 #22
0
        // GETTERS

        public byte[] getNodeDataRaw(String path, bool watch)
        {
            byte[] result = null;
            if (!String.IsNullOrEmpty(path))
            {
                try
                {
                    return(zk.GetData(path, this.doWatch, zk.Exists(path, false)));
                }
                catch (ZooKeeperNet.KeeperException ke)
                {
                    this.close();
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
コード例 #23
0
 public virtual void TestGetActiveData()
 {
     // get valid active data
     byte[] data = new byte[8];
     Org.Mockito.Mockito.When(mockZK.GetData(Org.Mockito.Mockito.Eq(ZkLockName), Org.Mockito.Mockito
                                             .Eq(false), Org.Mockito.Mockito.AnyObject <Stat>())).ThenReturn(data);
     Assert.Equal(data, elector.GetActiveData());
     Org.Mockito.Mockito.Verify(mockZK, Org.Mockito.Mockito.Times(1)).GetData(Org.Mockito.Mockito
                                                                              .Eq(ZkLockName), Org.Mockito.Mockito.Eq(false), Org.Mockito.Mockito.AnyObject <Stat
                                                                                                                                                             >());
     // active does not exist
     Org.Mockito.Mockito.When(mockZK.GetData(Org.Mockito.Mockito.Eq(ZkLockName), Org.Mockito.Mockito
                                             .Eq(false), Org.Mockito.Mockito.AnyObject <Stat>())).ThenThrow(new KeeperException.NoNodeException
                                                                                                                ());
     try
     {
         elector.GetActiveData();
         NUnit.Framework.Assert.Fail("ActiveNotFoundException expected");
     }
     catch (ActiveStandbyElector.ActiveNotFoundException)
     {
         Org.Mockito.Mockito.Verify(mockZK, Org.Mockito.Mockito.Times(2)).GetData(Org.Mockito.Mockito
                                                                                  .Eq(ZkLockName), Org.Mockito.Mockito.Eq(false), Org.Mockito.Mockito.AnyObject <Stat
                                                                                                                                                                 >());
     }
     // error getting active data rethrows keeperexception
     try
     {
         Org.Mockito.Mockito.When(mockZK.GetData(Org.Mockito.Mockito.Eq(ZkLockName), Org.Mockito.Mockito
                                                 .Eq(false), Org.Mockito.Mockito.AnyObject <Stat>())).ThenThrow(new KeeperException.AuthFailedException
                                                                                                                    ());
         elector.GetActiveData();
         NUnit.Framework.Assert.Fail("KeeperException.AuthFailedException expected");
     }
     catch (KeeperException.AuthFailedException)
     {
         Org.Mockito.Mockito.Verify(mockZK, Org.Mockito.Mockito.Times(3)).GetData(Org.Mockito.Mockito
                                                                                  .Eq(ZkLockName), Org.Mockito.Mockito.Eq(false), Org.Mockito.Mockito.AnyObject <Stat
                                                                                                                                                                 >());
     }
 }
コード例 #24
0
        public void Process(WatchedEvent @event)
        {
            // 全部重新 watch
            zk.GetData(@event.Path, this, null);
            zk.Exists(@event.Path, this);
            zk.GetChildren(@event.Path, this);

            Console.WriteLine("33receive watch notify:");
            Console.WriteLine("  path is : {0}", @event.Path);
            Console.WriteLine("  state is : {0}", @event.State);
            Console.WriteLine("  type is : {0}", @event.Type);
        }
コード例 #25
0
        public void Process(WatchedEvent @event)
        {
            if (@event.State == KeeperState.SyncConnected && _connectedSignal.CurrentCount != 0)
            {
                _connectedSignal.Signal();
                Status = "Connection Established!";
            }

            AppendLineShow(String.Format("Just hand an event: {0} ", @event.Type));

            if (@event.Type == EventType.NodeChildrenChanged)
            {
                const string pdfPath = "/PDFConverter";

                // List znodes + values
                try
                {
                    // Place the watcher again
                    Zk.GetChildren(pdfPath, true);

                    var children = Zk.GetChildren(pdfPath, false);
                    IEnumerable <string> enumerable = children as string[] ?? children.ToArray();

                    if (enumerable.IsEmpty())
                    {
                        AppendLineShow("No members in znode: " + pdfPath);
                    }
                    else
                    {
                        AppendLineShow("\n======= Z =======");
                        foreach (var child in enumerable)
                        {
                            var path = pdfPath + "/" + child;
                            var data = Zk.GetData(path, this, null /*stat*/);
                            AppendLineShow(child + "  -  " + (data != null ? Encoding.UTF8.GetString(data) : ""));
                        }
                        AppendLineShow("\n");
                    }
                }
                catch (KeeperException.NoNodeException e)
                {
                    AppendLineShow("Znode does not exist!");
                }
                catch (KeeperException.SessionExpiredException e)
                {
                    AppendLineShow("The session expired!");
                }
                catch (InvalidOperationException e)
                {
                    AppendLineShow("Too many '/'!");
                }
            }
        }
コード例 #26
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure(new FileInfo("zookeeperDemo.log4net"));

            zookeeper = new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 10), new ZooKeeper_Watch_Usage());
            manualWaitHandler.WaitOne();

            //ASYNC_VerifyZookeeper();

            string path     = "/zk-book";
            var    testStat = zookeeper.Exists(path, false);

            if (testStat == null)
            {
                zookeeper.Create(path, "123".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral);
            }


            var pathData = zookeeper.GetData(path, true, null);

            Console.WriteLine("The path's data(watched):{0}", System.Text.UTF8Encoding.UTF8.GetString(pathData));

            Console.WriteLine("begin to changed the data of path:{0}, which is watched.", path);
            zookeeper.SetData(path, "f**k you".GetBytes(), -1);
            Console.WriteLine("change data of path:{0} is finished, which is watched.", path);

            var newPath = "/ACID";

            zookeeper.Create(newPath, "AAAA".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral);
            var acidData = zookeeper.GetData(newPath, false, null);

            Console.WriteLine("The new created node's data(Unwatched):{0}", System.Text.UTF8Encoding.UTF8.GetString(acidData));

            Console.WriteLine("begin to changed the data of path:{0}, which is UNwatched.", newPath);
            zookeeper.SetData(newPath, "laoHUYou".GetBytes(), -1);
            Console.WriteLine("change data of path:{0} is finished, which is Unwatched.", newPath);

            Console.ReadLine();
        }
コード例 #27
0
        static void Main(string[] args)
        {
            IZooKeeper zk   = new ZooKeeper("127.0.0.1:2181", TimeSpan.FromHours(1), null);
            var        root = zk.Create("/root", Encoding.UTF8.GetBytes("123456"), null, CreateMode.Ephemeral);

            Console.WriteLine(root);

            var t = zk.GetData("/root", null, null);

            Console.WriteLine(t);

            Console.ReadKey();
        }
コード例 #28
0
 /// <summary>
 /// 获取路径的值
 /// </summary>
 /// <param name="path">路径</param>
 /// <param name="watcher">监视器</param>
 /// <param name="stat">状态信息</param>
 /// <returns></returns>
 public string GetData(string path, IWatcher watcher, Stat stat = null)
 {
     try
     {
         byte[] data = ZooKeeper.GetData(path, watcher, stat);
         return(Encoding.UTF8.GetString(data));
     }
     catch (Exception ex)
     {
         LogManager.GetLogger().Error(string.Format("DisconfClient.ZooKeeperClient.GetData(path={0}),ex:{1}", path, ex));
         throw;
     }
 }
コード例 #29
0
        public void ProcessResult(KeeperException.Code rc, String path, Object ctx, Stat stat)
        {
            bool exists;

            switch (rc)
            {
            case KeeperException.Code.OK:
                exists = true;
                break;

            case KeeperException.Code.NONODE:
                exists = false;
                break;

            case KeeperException.Code.SESSIONEXPIRED:
            case KeeperException.Code.NOAUTH:
                Dead = true;
                _listener.Closing(rc);
                return;

            default:
                // Retry errors
                _zk.Exists(_znode, true);
                return;
            }

            byte[] b = null;
            if (exists)
            {
                try
                {
                    b = _zk.GetData(_znode, false, null);
                }
                catch (KeeperException e)
                {
                    // We don't need to worry about recovering now. The watch
                    // callbacks will kick off any exception handling
                    //TODO
                }
                catch (Exception e)
                {
                    return;
                }
            }
            if ((b == null && b != _prevData) ||
                (b != null && !Equals(_prevData, b)))
            {
                _listener.Exists(b);
                _prevData = b;
            }
        }
コード例 #30
0
 static void Main(string[] args)
 {
     using (ZooKeeper zk = new ZooKeeper(ConfigServiceHelper.ZKServer, TimeSpan.FromSeconds(ConfigServiceHelper.ZKSessionTimeOut), null))
     {
         ZooKeeper.WaitUntilConnected(zk);
         string cookieNameKeyPath = string.Format("{0}/{1}", ConfigServiceHelper.ZKRootPathWithAppID, "CookieKeyName");
         if (zk.Exists(cookieNameKeyPath, false) != null)
         {
             byte[] _nodeValue = zk.GetData(cookieNameKeyPath, false, null);
             Console.WriteLine(Encoding.UTF8.GetString(_nodeValue));
         }
     }
     Console.ReadLine();
 }
コード例 #31
0
        public static void Watch()
        {
            // 这里注册的 watch 实例会覆盖 new Zookeeper() 时指定的 watch 实例
            // 如果注册多个,则会把最后注册的覆盖之前注册的
            zk.Register(new WatchCommon(zk));
            zk.Register(new WatchCommon3(zk));

            // 3 种添加 watch 的方式
            Stat stat = new Stat();

            // 1. 这种方式增加 watch ,只能watch 此节点的数据更新和删除事件
            zk.GetData("/test/t1", true, stat);                // /test/t1 要事先存在
            zk.GetData("/test/t2", new WatchCommon(zk), stat); // 单独指定实例,不使用 注册时的实例   /test/t2 要事先存在

            // 2. 这种方式增加 watch ,可以watch 此节点的数据更新和删除事件,以及节点创建事件
            zk.Exists("/test/t3", true);   //  /test/t3 可事先不存在

            // 3. 这种方式增加的 watch, 可以 watch 此节点的删除事件,以及子节点的创建和删除事件
            zk.GetChildren("/test/t3", true); //  /test/t3 要事先存在

            /*
             * 上面 语句 zk.Exists("/test/t3", true);  和 zk.GetChildren("/test/t3", true); watch 中都包含 删除事件,
             * 那如果把 /test/t3 删除,是否会收到两次通知呢?
             * 测试结果是只收到一次通知,因为 watch 实例是一样的,
             * 如果 后面的语句改成 zk.GetChildren("/test/t3", new WatchCommon2()); 即单独的 watch 实例,
             * 则把 /test/t3 删除,每个实例都会收到通知
             */

            /* 注意点:
             * 1.watch是一次性触发的,如果获取一个watch事件并希望得到新变化的通知,需要重新设置watch
             * 2.watch是一次性触发的并且在获取watch事件和设置新watch事件之间有延迟,所以不能可靠的观察到节点的每一次变化。要认识到这一点。
             */

            var childWatchList = zk.ChildWatches;
            var dataWatchList  = zk.DataWatches;
            var existWatchList = zk.ExistWatches;
        }
コード例 #32
0
        public bool UpdateNodeValue(string nodePath, string newNodeValue, ref string message)
        {
            try
            {
                byte[] newData = Encoding.UTF8.GetBytes(newNodeValue);

                using (ZooKeeper zk = new ZooKeeper(AppSettingsHelper.ZKServer, TimeSpan.FromSeconds(AppSettingsHelper.ZKSessionTimeOut), null))
                {
                    ZooKeeper.WaitUntilConnected(zk);

                    Stat stat = zk.Exists(nodePath, false);
                    if (stat == null)
                    {
                        message = string.Format("该节点【{0}】已被别人删除。", nodePath);
                        return(false);
                    }

                    byte[] oldValue = zk.GetData(nodePath, false, stat);
                    if (oldValue == null || oldValue.Length < 1)
                    {
                        if (string.IsNullOrWhiteSpace(newNodeValue))
                        {
                            message = "和原来的值一样,所以无需更新。";
                            return(false);
                        }
                    }
                    string oldValueStr = string.Empty;
                    if (oldValue != null && oldValue.Length > 0)
                    {
                        oldValueStr = Encoding.UTF8.GetString(oldValue);
                    }
                    if (newNodeValue.Equals(oldValueStr))
                    {
                        message = "和原来的值一样,所以无需更新。";
                        return(false);
                    }

                    Stat newStat = zk.SetData(nodePath, newData, stat.Version);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                message = string.Format("JinRi.Fx.Manage:{0}UpdateNodeValue()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                log.Error(message);
                message = string.Format("UpdateNodeValue()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                return(false);
            }
        }
コード例 #33
0
        public CollectionClusterState GetClusterState(string zkHost, string collectionName)
        {
            var w = new watcher();
            var zk = new ZooKeeper(zkHost, TimeSpan.FromSeconds(1), w);
            w.WaitUntilConnected(1);

            //var nodes = zk.GetChildren("/live_nodes", false).ToList();

            var clusterState = zk.GetData("/clusterstate.json", false, null);
            var json = Encoding.Default.GetString(clusterState);

            ClusterState state = ClusterState.FromJson(json);

            return new CollectionClusterState(state.Collections[collectionName]);
        }
コード例 #34
0
ファイル: Program.cs プロジェクト: ittray/LocalDemo
        private static bool checkMaster(ZooKeeper zk)
        {
            while (true)
            {
                try
                {
                    Stat stat = new Stat();
                    byte[] data = zk.GetData("/master", false, stat);
                    var isLeader = System.Text.Encoding.UTF8.GetString(data).Equals("230");
                    return true;
                }
                catch (KeeperException.NoNodeException)
                {

                    return false;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }