Zookeeper.NET Client(二)【官方驱动 开发入门】

首先项目结构很简单,如图:


接下来是Program.cs内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ZooKeeperClient;
using ZooKeeperNet;

namespace ZkTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string _address = "127.0.0.1:2181";
            IZooKeeperFactory _factory=ZooKeeperFactory.Instance;
            
            var zk = _factory.Connect(_address);
 
            if (zk.Exists("/ConnectionTest", true)==null)
            {
                // 创建一个目录节点,不进行ACL权限控制,节点为永久性的  
                zk.Create("/ConnectionTest", "testRootData".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                // 创建一个子目录节点
                //临时节点:客户端会话失效或连接关闭后,该节点会被自动删除,且不能再临时节点下面创建子节点,否则报如下错:org.apache.zookeeper.KeeperException$NoChildrenForEphemeralsException;
                //CreateMode.Ephemeral
                // 临时顺序节点:基本特性与临时节点一致,创建节点的过程中,zookeeper会在其名字后自动追加一个单调增长的数字后缀,作为新的节点名
                //CreateMode.EphemeralSequential
                //持久节点:节点创建后,会一直存在,不会因客户端会话失效而删除
                //CreateMode.Persistent
                //持久顺序节点:基本特性与持久节点一致,创建节点的过程中,zookeeper会在其名字后自动追加一个单调增长的数字后缀,作为新的节点名
                //CreateMode.PersistentSequential
                zk.Create("/ConnectionTest/testChildPathOne", "testChildDataOne".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent); 
            }
             
            var state = zk.State;
            Thread.Sleep(2000);
            if (state.Equals(ZooKeeper.States.CONNECTED))
            {
                 string conTestData= Encoding.Default.GetString(zk.GetData("/ConnectionTest", true, null));
                 Console.WriteLine("取出根目录节点数据:"+conTestData);
                // 取出子目录节点列表
                 zk.GetChildren("/ConnectionTest", true).ToList().ForEach(delegate(String NodeName)
                     {
                         Console.WriteLine("子目录节点名称:"+NodeName);
                     }
                     );

                 //取出子目录节点数据,返回byte[] 
                 string childTestData = Encoding.Default.GetString(zk.GetData("/ConnectionTest/testChildPathOne", true, null));
                 Console.WriteLine("取出子目录节点数据:"+childTestData);

                //修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉  
                 zk.SetData("/ConnectionTest/testChildPathOne", "CHILDGeekModify".GetBytes(), -1);
                 //查询修改的数据
                 childTestData = Encoding.Default.GetString(zk.GetData("/ConnectionTest/testChildPathOne", true, null));
                 Console.WriteLine("取出子目录节点修改后数据为:" + childTestData);
                //删除/ConnectionTest/testChildPathOne这个节点,第二个参数为版本,-1的话直接删除,无视版本 
                 //zk.Delete("/ConnectionTest/testChildPathOne", -1);  
             
            }
            zk.Dispose();
            Console.WriteLine("---------------------------------------------------");
          
            Console.ReadKey();
        }
    }
}

接下来看Watcher.cs代码:

namespace ZooKeeperClient
{
    internal class Watcher : IWatcher
    {
        public void Process(WatchedEvent @event)
        {
            if (@event.Type == EventType.NodeDataChanged)
            {
                Console.WriteLine(@event.Path + "   此路径节点变化了!");
            }  
        }
    }
}

很重要的ZooKeeperFactory.cs和IZooKeeperFactory.cs:

using System;
using ZooKeeperNet;

namespace ZooKeeperClient
{
    public interface IZooKeeperFactory
    {
        ZooKeeper Connect(string address);
        
        ZooKeeper Connect(string address, TimeSpan timeoutSpan);
        
        ZooKeeper Connect(string address, TimeSpan timeoutSpan, IWatcher watcher);

        ZooKeeper Connect(string address, TimeSpan timeoutSpan, IWatcher watcher, long sessionId, byte[] password);
    }
}

using System;
using ZooKeeperNet;

namespace ZooKeeperClient
{
    public sealed class ZooKeeperFactory : IZooKeeperFactory
    {
        public static IZooKeeperFactory Instance = new ZooKeeperFactory();

        private ZooKeeperFactory() { }



        //创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法   
        public ZooKeeper Connect(string address)
        {
            return Connect(address, new TimeSpan(0, 0, 0, 30), new Watcher());
        }

        public ZooKeeper Connect(string address, TimeSpan timeoutSpan)
        {
            return Connect(address, timeoutSpan, new Watcher());
        }

        public ZooKeeper Connect(string address, TimeSpan timeoutSpan, IWatcher watcher)
        {
            return new ZooKeeper(address, timeoutSpan, watcher);
        }

        public ZooKeeper Connect(string address, TimeSpan timeoutSpan, IWatcher watcher, long sessionId, byte[] password)
        {
            return new ZooKeeper(address, timeoutSpan, watcher, sessionId, password);
        }
    }
}

最终结果如图:




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
什么是ZooKeeperZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。 ZooKeeper的目标就是封装好复杂易出错的关键服务,将简单易用的接口和性能高效、功能稳定的系统提供给用户。 Rabbit ZooKeeper Extensions 该项目使用了 Apache ZooKeeper .NET async Client 组件,除提供了基本的zk操作,还额外封装了常用的功能以便让.net开发者更好的使用zookeeper。 提供的功能 session过期重连 永久watcher 递归删除节点 递归创建节点 跨平台(支持.net core) 使用说明 创建连接 IZookeeperClient client = new ZookeeperClient(new ZookeeperClientOptions         {             ConnectionString = "172.18.20.132:2181",             BasePath = "/", //default value             ConnectionTimeout = TimeSpan.FromSeconds(10), //default value             SessionTimeout = TimeSpan.FromSeconds(20), //default value             OperatingTimeout = TimeSpan.FromSeconds(60), //default value             ReadOnly = false, //default value             SessionId = 0, //default value             SessionPasswd = null //default value         }); 创建节点 var data = Encoding.UTF8.GetBytes("2016"); //快速创建临时节点 await client.CreateEphemeralAsync("/year", data); await client.CreateEphemeralAsync("/year", data, ZooDefs.Ids.OPEN_ACL_UNSAFE); //快速创建永久节点 await client.CreatePersistentAsync("/year", data); await client.CreatePersistentAsync("/year", data, ZooDefs.Ids.OPEN_ACL_UNSAFE); //完整调用 await client.CreateAsync("/year", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); //递归创建 await client.CreateRecursiveAsync("/microsoft/netcore/aspnet", data, CreateMode.PERSISTENT); 获取节点数据 IEnumerable data = await client.GetDataAsync("/year"); Encoding.UTF8.GetString(data.ToArray()); 获取子节点 IEnumerable children= await client.GetChildrenAsync("/microsoft"); 判断节点是否存在 bool exists = await client.ExistsAsync("/year"); 删除节点 await client.DeleteAsync("/year"); //递归删除 bool success = await client.DeleteRecursiveAsync("/microsoft"); 更新数据 Stat stat = await client.SetDataAsync("/year", Encoding.UTF8.GetBytes("2017")); 订阅数据变化 await client.Subscrib

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值