[ZooKeeper.net] 1 模仿dubbo实现一个简要的http服务的注册 基于webapi

时间:2022-06-28 08:20:53

今天来试着模仿下dubbo实现一个简要的http服务的注册,虽说是模仿不过是很廉价的那种,只是模仿了一点点点......

先放上demo目录结构:

开头还是把ZooKeeper的一些简要介绍搬过来看看,这样让大家也能多了解点儿:

ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,它包含一个简单的原语集,分布式应用程序可以基于它实现同步服务,配置维护和命名服务等。Zookeeper是hadoop的一个子项目,,其发展历程无需赘述。在分布式应用中,由于工程师不能很好地使用锁机制,以及基于消息的协调机制不适合在某些应用中使用,因此需要有一种可靠的、可扩展的、分布式的、可配置的协调机制来统一系统的状态。Zookeeper的目的就在于此。

      Zoopkeeper 提供了一套很好的分布式集群管理的机制,就是它这种基于层次型的目录树的数据结构,并对树中的节点进行有效管理,从而可以设计出多种多样的分布式的数据管理模型。

OK,更多介绍大家自行搜索吧,主要点【基于层次型的目录树的数据结构,并对树中节点进行有效管理】,这句话是不是可以理解就是树形结构,我也放个图,省的还要大家脑补......

                      

ps.有关ZooKeeper的安装不管是windows还是linux不论是单机还是集群网上一搜好多的,我用的zookeeper-3.4.6 windows版的

首先我们要获取到ZooKeeper.Net的客户端

首先定义个IZooKeeperFactory

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); }

然后ZooKeeperFactory 和 Watcher

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); } }

ZooKeeperFactory

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

Watcher

以上直接用于创建Zookeeper的实例,各个参数代码中也写了说明

然后我们创建UserServicesController 里面写了两个服务 1.User/sayhello  2.User/saybye