基于ZooKeeper的服务注册实现

简介

本文介绍在本地环境搭建ZooKeeper的伪集群环境的步骤,并且在Spring Boot环境下,如何使用ZooKeeper来注册服务。

本文参考了《架构探险》轻量级微服务架构 这本书。

本文示例代码:zookeeper-demo

搭建ZooKeeper伪集群

下载并安装

在官网下载ZooKeeper相关包后,解压到/etc/zookeeper下,并复制3份(ZooKeeper构建集群时,官网建议部署奇数个节点)。


安装ZooKeeper

修改配置

将conf/zoo_sample.cfg重命名为zoo.cfg,并将节点1修改为如下配置,具体意思请百度,这里不详细展开,因为这里配置的伪集群,所以要求各端口都不一样。

注意:在路径/home/billjiang/zookeeper/zkServer1目录下需要建立一个myid文件,并在文件中写入内容1

节点1配置

# The number of milliseconds of each tick
tickTime=2000
initLimit=10
syncLimit=5
dataDir=/home/billjiang/zookeeper/zkServer1
clientPort=2181
#cluster
server.1=127.0.0.1:2888:3888
server.2=127.0.0.1:2889:3889
server.3=127.0.0.1:2890:3890

节点2配置

# The number of milliseconds of each tick
tickTime=2000
initLimit=10
syncLimit=5
dataDir=/home/billjiang/zookeeper/zkServer2
clientPort=2182
#cluster
server.1=127.0.0.1:2888:3888
server.2=127.0.0.1:2889:3889
server.3=127.0.0.1:2890:3890

节点3配置

# The number of milliseconds of each tick
tickTime=2000
initLimit=10
syncLimit=5
dataDir=/home/billjiang/zookeeper/zkServer3
clientPort=2183
#cluster
server.1=127.0.0.1:2888:3888
server.2=127.0.0.1:2889:3889
server.3=127.0.0.1:2890:3890

批量启动集群shell脚本

为了启动集群,可以一个一个启动,也可以编写shell脚本批量启动:

zookeeper_start.sh

    #!/bin/bash  
    SERVERS="zkServer1 zkServer2 zkServer3"  
      
    for SERVER in $SERVERS  
    do  
          echo "当前"$SERVER"正在启动...................."  
           #ssh root@$SERVER "source /etc/profile;/usr/apps/zookeeper-3.4.9/bin/zkServer.sh start"  
          sudo /etc/zookeeper/$SERVER/bin/zkServer.sh start
          echo $SERVER"启动结束--------------------------------------------"                                                                         
    done  

当然也可以编写批量停止的shell脚本。执行批量启动命令后,如下:


启动ZooKeeper集群

启动集群后,可使用bin/zkCli.sh命令查看ZooKeeper的节点数据。

以上完成了ZooKeeper伪集群的搭建。

服务注册实现

为了演示服务在ZooKeeper上的注册过程,本文这里启动了一个Maven项目zookeeper-learn,项目包含三个module

  • core 注册的核心逻辑
  • client 客户端服务1
  • client2 客户端服务2
zookeeper-learn

其中client/client2项目都依赖了core项目。在它们的pom.xml配置了该依赖

<dependency>
            <groupId>com.cnpc</groupId>
            <artifactId>core</artifactId>
            <version>0.0.1-SNAPSHOT</version>
</dependency>

core项目的核心代码

定义服务注册接口ServiceRegistry

package com.example.core;

public interface ServiceRegistry {
    /**
     * 注册服务信息
     *
     * @param serviceName    服务名称
     * @param serviceAddress 服务地址
     */
    void register(String serviceName, String serviceAddress);

}

服务注册实现ServiceRegistryImpl
该服务实现将连接ZooKeeper集群,创建节点,并把服务的调用地址作为节点的值存储在该节点上。

package com.example.core;

import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

@Component
public class ServiceRegistryImpl implements ServiceRegistry, Watcher {
    private static Logger logger = LoggerFactory.getLogger(ServiceRegistryImpl.class);
    private static CountDownLatch latch = new CountDownLatch(1);
    private ZooKeeper zk;
    private static final int SESSION_TIMEOUT = 5000;
    public ServiceRegistryImpl() {

    }

    public ServiceRegistryImpl(String zkServers) {
        try {
            zk = new ZooKeeper(zkServers, SESSION_TIMEOUT, this);
            latch.await();
            logger.debug("connected to zookeeper");
        } catch (Exception ex) {
            logger.error("create zookeeper client failure", ex);
        }
    }

    private static final String REGISTRY_PATH = "/registry";

    @Override
    public void register(String serviceName, String serviceAddress) {
        try {
            String registryPath = REGISTRY_PATH;
            if (zk.exists(registryPath, false) == null) {
                zk.create(registryPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                logger.debug("create registry node:{}", registryPath);
            }
            //创建服务节点(持久节点)
            String servicePath = registryPath + "/" + serviceName;
            if (zk.exists(servicePath, false) == null) {
                zk.create(servicePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                logger.debug("create service node:{}", servicePath);
            }
            //创建地址节点
            String addressPath = servicePath + "/address-";
            String addressNode = zk.create(addressPath, serviceAddress.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            logger.debug("create address node:{} => {}", addressNode, serviceAddress);
        } catch (Exception e) {
            logger.error("create node failure", e);
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected)
            latch.countDown();
    }
}

客户端注册服务

客户端在启动时,会将自身服务节点注册到ZooKeeper集群中。

application.properties配置

server.address=127.0.0.1
server.port=8080
registry.servers=127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183

服务注册配置RegistryConfig
这样客户端可以读取appliaction.properties的ZooKeeper配置

package com.example.client;

import com.example.core.ServiceRegistry;
import com.example.core.ServiceRegistryImpl;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@ConfigurationProperties(prefix = "registry")
public class RegistryConfig {

    private String servers;

    @Bean
    public ServiceRegistry serviceRegistry() {
        return new ServiceRegistryImpl(servers);
    }

    public void setServers(String servers) {
        this.servers = servers;
    }
}

用来测试的服务接口:TestController

@RestController
public class TestController {

    @RequestMapping(name="HelloService",method = RequestMethod.GET,path = "/hello")
    public String hello(){
        return "Hello";
    }
}

在项目启动的时候会将注解中name属性有值的方法注册到ZooKeeper集群中,

package com.example.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.example.core.ServiceRegistry;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

@Component
public class WebListener implements ServletContextListener {

    @Value("${server.address}")
    private String serverAddress;

    @Value("${server.port}")
    private int serverPort;

    @Autowired
    public ServiceRegistry serviceRegistry;


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext=sce.getServletContext();
        ApplicationContext applicationContext= WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        RequestMappingHandlerMapping mapping=applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo,HandlerMethod> infoMap=mapping.getHandlerMethods();
        for (RequestMappingInfo info : infoMap.keySet()) {
            String serviceName=info.getName();
            System.out.println("-----------------"+serviceName);
            if(serviceName!=null){
                //注册服务
                serviceRegistry.register(serviceName,String.format("%s:%d",serverAddress,serverPort));
            }
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

同样在client2项目中,相同的代码,唯一的区别就是client2的application.properties的server.port=8082

同时启动两个client2项目后,通过bin/zkCli.sh命令,连接到任意的一台ZooKeeper节点(因为ZooKeeper几点之间数据会保持同步)。显示如下信息:

[zk: localhost:2181(CONNECTED) 18] ls /registry/HelloService
[address-0000000004, address-0000000003]

使用get查看子节点的值

get /registry/HelloService/address-0000000003
127.0.0.1:8080
cZxid = 0x100000026
ctime = Wed Aug 09 18:00:56 CST 2017
mZxid = 0x100000026
mtime = Wed Aug 09 18:00:56 CST 2017
pZxid = 0x100000026
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x15dc5782fe8000d
dataLength = 14
numChildren = 0

get /registry/HelloService/address-0000000004
127.0.0.1:8081
cZxid = 0x100000028
ctime = Wed Aug 09 18:03:05 CST 2017
mZxid = 0x100000028
mtime = Wed Aug 09 18:03:05 CST 2017
pZxid = 0x100000028
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x15dc5782fe8000e
dataLength = 14
numChildren = 0

当停掉一台客户端client后,再次使用ls 命令,只显示address-0000000004

以上代码完成了ZooKeeper的服务注册。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,306评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,657评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,928评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,688评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,105评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,024评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,159评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,937评论 0 212
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,689评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,851评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,325评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,651评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,364评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,192评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,985评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,154评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,955评论 2 279

推荐阅读更多精彩内容