1.基本介绍

命名服务是指通过指定的名字来获取资源或者服务的地址,提供者的信息。利用Zookeeper非常easy创建一个全局的路径,而这个路径就能够作为一个名字。它能够指向集群中的集群。提供的服务的地址,远程对象等。简单来说使用Zookeeper做命名服务就是用路径作为名字,路径上的数据就是其名字指向的实体。

阿里巴巴集团开源的分布式服务框架Dubbo中使用ZooKeeper来作为其命名服务,维护全局的服务地址列表。在Dubbo实现中:

服务提供者在启动的时候,向ZK上的指定节点/dubbo/${serviceName}/providers文件夹下写入自己的URL地址,这个操作就完毕了服务的公布

服务消费者启动的时候。订阅/dubbo/{serviceName}/providers文件夹下的提供者URL地址, 并向/dubbo/{serviceName} /consumers文件夹下写入自己的URL地址。

注意,全部向ZK上注冊的地址都是暂时节点。这样就行保证服务提供者和消费者可以自己主动感应资源的变化。

另外,Dubbo还有针对服务粒度的监控。方法是订阅/dubbo/{serviceName}文件夹下全部提供者和消费者的信息。

场景实践

上面的介绍已经满具体。实际实现起来也比較easy。以下讲讲模拟程序的主要特点。模拟程序有3个參数

  • -m 程序执行的方式,指定是服务提供者provider还是服务消费者consumer,或者是服务监控者monitor
  • -n 表示服务名称
  • -s 表示Zookeeper的服务地址IP:PORT

    执行命令例如以下:

    服务提供者:

    >nameservice -m provider -n query_bill -s172.17.0.36:2181

    服务消费者:

    >nameservice -m consumer -n query_bill -s172.17.0.36:2181

    服务监控者:

    >nameservice -m monitor -n query_bill -s172.17.0.36:2181

第一条命令是启动一个服务提供进程,它提供了一个名为query_bill的服务。程序首次执行时会创建

/NameService,/NameService/query_bill,/NameService/query_bill/provider,/NameService/query_bill/consumer/等几个路径。然后在服务提供进程在/NameService/query_bill/provider下创建暂时序列节点.

第二条命令是启动一个服务消费进程,它在/NameService/query_bill/consumer/下创建暂时序列节点,并watch/NameService/query_bill/provider的子节点变化事件。及时更新provider列表。

第三条命令是启动一个服务监控进程。它watch
/NameService/query_bill/provider
,/NameService/query_bill/consumer/两个路径的子节点变化,及时更新provider列表和comsumer列表。

完整的代码例如以下:

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include"zookeeper.h"
#include"zookeeper_log.h" enum MODE{PROVIDER_MODE,CONSUMER_MODE,MONITOR_MODE} g_mode;
char g_host[512]= "172.17.0.36:2181";
char g_service[512]={ 0 };
char g_path[512]="/NameService"; //watch function when child list changed
void zktest_watcher_g(zhandle_t* zh, int type, int state, const char* path, void* watcherCtx);
//show all process ip:pid
void show_list(zhandle_t *zkhandle,const char *path);
//if success,the g_mode will become MODE_MONITOR
void choose_mater(zhandle_t *zkhandle,const char *path);
//get localhost ip:pid
void getlocalhost(char *ip_pid,int len); void print_usage();
void get_option(int argc,const char* argv[]); /**********unitl*********************/
void print_usage()
{
printf("Usage : [nameservice] [-h] [-m mode] [-n servicename] [-s ip:port] \n");
printf(" -h Show help\n");
printf(" -m set mode:provider,consumer,monitor\n");
printf(" -n set servicename\n");
printf(" -s server ip:port\n");
printf("For example:\n");
printf(" nameservice -m provider -n query_bill -s172.17.0.36:2181 \n");
printf(" nameservice -m consumer -n query_bill -s172.17.0.36:2181 \n");
printf(" nameservice -m monitor -n query_bill -s172.17.0.36:2181 \n");
} void get_option(int argc,const char* argv[])
{
extern char *optarg;
int optch;
int dem = 1;
const char optstring[] = "hm:n:s:"; while((optch = getopt(argc , (char * const *)argv , optstring)) != -1 )
{
switch( optch )
{
case 'h':
print_usage();
exit(-1);
case '?':
print_usage();
printf("unknown parameter: %c\n", optopt);
exit(-1);
case ':':
print_usage();
printf("need parameter: %c\n", optopt);
exit(-1);
case 'm':
if (strcasecmp(optarg,"provider") == 0){
g_mode = PROVIDER_MODE;
}else if (strcasecmp(optarg,"consumer") == 0){
g_mode = CONSUMER_MODE;
}else{
g_mode = MONITOR_MODE;
}
break;
case 'n':
strncpy(g_service,optarg,sizeof(g_service));
break;
case 's':
strncpy(g_host,optarg,sizeof(g_host));
break;
default:
break;
}
}
}
void zktest_watcher_g(zhandle_t* zh, int type, int state, const char* path, void* watcherCtx)
{
/*
printf("watcher event\n");
printf("type: %d\n", type);
printf("state: %d\n", state);
printf("path: %s\n", path);
printf("watcherCtx: %s\n", (char *)watcherCtx);
*/ if(type == ZOO_CHILD_EVENT &&
state == ZOO_CONNECTED_STATE &&
g_mode == CONSUMER_MODE){ printf("providers list changed!\n");
show_list(zh,path);
}else if(type == ZOO_CHILD_EVENT &&
state == ZOO_CONNECTED_STATE &&
g_mode == MONITOR_MODE){ printf("providers or consumers list changed!\n"); char child_path[512];
printf("providers:\n");
sprintf(child_path,"%s/%s/provider",g_path,g_service);
show_list(zh,child_path); printf("consumers:\n");
sprintf(child_path,"%s/%s/consumer",g_path,g_service);
show_list(zh,child_path);
}
}
void getlocalhost(char *ip_pid,int len)
{
char hostname[64] = {0};
struct hostent *hent ; gethostname(hostname,sizeof(hostname));
hent = gethostbyname(hostname); char * localhost = inet_ntoa(*((struct in_addr*)(hent->h_addr_list[0]))); snprintf(ip_pid,len,"%s:%d",localhost,getpid());
} void show_list(zhandle_t *zkhandle,const char *path)
{ struct String_vector procs;
int i = 0;
char localhost[512]={0}; getlocalhost(localhost,sizeof(localhost)); int ret = zoo_get_children(zkhandle,path,1,&procs); if(ret != ZOK){
fprintf(stderr,"failed to get the children of path %s!\n",path);
}else{
char child_path[512] ={0};
char ip_pid[64] = {0};
int ip_pid_len = sizeof(ip_pid);
printf("--------------\n");
printf("ip\tpid\n");
for(i = 0; i < procs.count; ++i){
sprintf(child_path,"%s/%s",path,procs.data[i]);
//printf("%s\n",child_path);
ret = zoo_get(zkhandle,child_path,0,ip_pid,&ip_pid_len,NULL);
if(ret != ZOK){
fprintf(stderr,"failed to get the data of path %s!\n",child_path);
}else if(strcmp(ip_pid,localhost)==0){
printf("%s(Master)\n",ip_pid);
}else{
printf("%s\n",ip_pid);
}
}
} for(i = 0; i < procs.count; ++i){
free(procs.data[i]);
procs.data[i] = NULL;
}
}
int create(zhandle_t *zkhandle,const char *path,const char *ctx,int flag)
{
char path_buffer[512];
int bufferlen=sizeof(path_buffer); int ret = zoo_exists(zkhandle,path,0,NULL);
if(ret != ZOK){
ret = zoo_create(zkhandle,path,ctx,strlen(ctx),
&ZOO_OPEN_ACL_UNSAFE,flag,
path_buffer,bufferlen);
if(ret != ZOK){
fprintf(stderr,"failed to create the path %s!\n",path);
}else{
printf("create path %s successfully!\n",path);
}
} return ZOK;
} int main(int argc, const char *argv[])
{
int timeout = 30000;
char path_buffer[512];
int bufferlen=sizeof(path_buffer);
int ret = 0;
zoo_set_debug_level(ZOO_LOG_LEVEL_ERROR); //设置日志级别,避免出现一些其它信息 get_option(argc,argv); zhandle_t* zkhandle = zookeeper_init(g_host,zktest_watcher_g, timeout, 0, (char *)"NameService Test", 0); if (zkhandle ==NULL)
{
fprintf(stderr, "Error when connecting to zookeeper servers...\n");
exit(EXIT_FAILURE);
} create(zkhandle,g_path,"NameService Test",0); sprintf(path_buffer,"%s/%s",g_path,g_service);
create(zkhandle,path_buffer,"NameService Test",0); sprintf(path_buffer,"%s/%s/provider",g_path,g_service);
create(zkhandle,path_buffer,"NameService Test",0); sprintf(path_buffer,"%s/%s/consumer",g_path,g_service);
create(zkhandle,path_buffer,"NameService Test",0); if(g_mode == PROVIDER_MODE){ char localhost[512]={0};
getlocalhost(localhost,sizeof(localhost)); char child_path[512];
sprintf(child_path,"%s/%s/provider/",g_path,g_service);
ret = zoo_create(zkhandle,child_path,localhost,strlen(localhost),
&ZOO_OPEN_ACL_UNSAFE,ZOO_SEQUENCE|ZOO_EPHEMERAL,
path_buffer,bufferlen);
if(ret != ZOK){
fprintf(stderr,"failed to create the child_path %s,buffer:%s!\n",child_path,path_buffer);
}else{
printf("create child path %s successfully!\n",path_buffer);
} }else if (g_mode == CONSUMER_MODE){ char localhost[512]={0};
getlocalhost(localhost,sizeof(localhost)); char child_path[512];
sprintf(child_path,"%s/%s/consumer/",g_path,g_service);
ret = zoo_create(zkhandle,child_path,localhost,strlen(localhost),
&ZOO_OPEN_ACL_UNSAFE,ZOO_SEQUENCE|ZOO_EPHEMERAL,
path_buffer,bufferlen);
if(ret != ZOK){
fprintf(stderr,"failed to create the child_path %s,buffer:%s!\n",child_path,path_buffer);
}else{
printf("create child path %s successfully!\n",path_buffer);
} sprintf(child_path,"%s/%s/provider",g_path,g_service);
show_list(zkhandle,child_path); }else if(g_mode == MONITOR_MODE){
char child_path[512];
printf("providers:\n");
sprintf(child_path,"%s/%s/provider",g_path,g_service);
show_list(zkhandle,child_path); printf("consumers:\n");
sprintf(child_path,"%s/%s/consumer",g_path,g_service);
show_list(zkhandle,child_path);
} getchar(); zookeeper_close(zkhandle); return 0;
}

版权声明:本文博客原创文章,博客,未经同意,不得转载。

Zookeeper实践方案:(4)命名服务的更多相关文章

  1. ZooKeeper实践方案:(7) 分布式锁

    1.基本介绍 分布式锁是控制分布式系统之间同步訪问共享资源的一种方式,须要相互排斥来防止彼此干扰来保证一致性. 利用Zookeeper的强一致性能够完毕锁服务.Zookeeper的官方文档是列举了两种 ...

  2. 中小型研发团队架构实践:分布式协调服务ZooKeeper

    一.ZooKeeper 是什么 Apache ZooKeeper 由 Apache Hadoop 的子项目发展而来,于 2010 年 11 月正式成为了 Apache 的顶级项目. 相关厂商内容 优秀 ...

  3. AMQ学习笔记 - 14. 实践方案:基于ZooKeeper + ActiveMQ + replicatedLevelDB的主从部署

    概述 基于ZooKeeper + ActiveMQ + replicatedLevelDB,在Windows平台的主从部署方案. 主从部署可以提供数据备份.容错[1]的功能,但是不能提供负载均衡的功能 ...

  4. ZooKeeper实现命名服务

    使用场景  命名服务就是提供名称的服务,Zookeeper的命名服务有两个应用方面.一个是提供类似JNDI功能,另一个是制作分布式的序列号生成器.         JNDI功能,我们利用Zookeep ...

  5. zookeeper命名服务

    zookeeper概念 zooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,底层组成单元是znode,对于zookeeper来说,所有的功能都是基于znode来实现的,因此有万物皆节点 ...

  6. zookeeper全局数据一致性及其典型应用(发布订阅、命名服务、帮助其他集群选举)

    ZooKeeper全局数据一致性: 全局数据一致:集群中每个服务器保存一份相同的数据副本,client 无论连接到哪个服务器,展示的数据都是一致的,这是最重要的特征. 那么zookeeper集群是怎样 ...

  7. springcloud实践(一)服务发现:Eureka

    Eureka 入门 是什么? Eureka 是 Netflix 开源的一个 RESTful服务,主要用于服务注册与发现. 它由Eureka server 和Eureka client组成. Eurek ...

  8. 全链路实践Spring Cloud 微服务架构

    Spring Cloud 微服务架构全链路实践Spring Cloud 微服务架构全链路实践 阅读目录: 网关请求流程 Eureka 服务治理 Config 配置中心 Hystrix 监控 服务调用链 ...

  9. nginx及其常用实践方案

    nginx及其常用实践方案 1.概述 1.1 什么是nginx? 1.2 什么是反向代理? 2.nginx常用命令 3.ningx配置实践 3.1 nginx.conf基础配置项 3.2 http 反 ...

随机推荐

  1. 深入应用看本质之-ICMP(1)

    在网络层的学习时我们easy忽略IP的一个字段--存活时间 以下是百度上的解释 (8)生存时间 占8位,生存时间字段经常使用的的英文缩写是TTL(Time To Live),表明是数据报在网络中的寿命 ...

  2. uva-211-The Domino Effect

    http://uva.onlinejudge.org/external/2/211.html http://uva.onlinejudge.org/external/2/211.pdf 题意:每一种骨 ...

  3. jQuery EasyUI API 中文文档 - 布局(Layout)

    <html> <head> <script src="jquery-easyui/jquery.min.js"></script> ...

  4. projecteuler----&gt;problem=9----Special Pythagorean triplet

    title: A Pythagorean triplet is a set of three natural numbers, a b c, for which, a2 + b2 = c2 For e ...

  5. 基于S5pv210流媒体server的实现之网络摄像头(by liukun321 咕唧咕唧)

    这里仅介绍流媒体server端的实现思路.及编码注意问题,不会贴代码的详细实现. 直接入正题先介绍一下系统硬件框架: server端连接PC机用VLC播放例如以下图: server端应用程序能够分为图 ...

  6. java中怎么终止一个线程的执行----个人学习心得

    参考了一下两个网站的介绍: ①:http://blog.csdn.net/liuhanhan512/article/details/7077601 ②:http://www.blogjava.net/ ...

  7. POJ 3458 Colour Sequence(简单题)

    [题意简述]:事实上题意我也没有特别看懂.可是依据它少许的题目描写叙述加上给的例子.就大胆的做了例如以下的推測: 就是说,如今给出一串字符s.然后紧接着给出可见的字符串visible还有隐藏的字符串h ...

  8. SVN的svnlook命令

    svnlook命令集(zhuanzai) 2011-12-08 17:00:30|  分类: System and CVS|字号 订阅     svnlook 名称 svnlook author — ...

  9. HDU 3830 Checkers

    意甲冠军: 有三件  所有其他棋子可以跳  不能分开的两个跳跃  当被问及状态u为了国家v最低短跳转 思路: 对于一个状态三个棋子的位置能够设为 x y z  (小到大) 仅仅有当y-x=z-y的时候 ...

  10. LINUX设备驱动程序的注意事项(两)建设和执行模块

             <一>:设置測试系统 首先准备好一个内核源代码树,构造一个新内核,然后安装到自己的系统中.           <二>:HelloWorld模块 #inclu ...