当前位置: 代码网 > it编程>编程语言>Java > Zookeeper详解

Zookeeper详解

2024年08月06日 Java 我要评论
Curator 是 Apache ZooKeeper 的Java客户端库,目标是简化 ZooKeeper 客户端的使用常见的ZooKeeper Java API :原生Java APIZkClientCuratorCurator 最初是 Netfix 研发的,后来捐献了 Apache 基金会,目前是 Apache 的顶级项目。

1.zookeeper概述

1.zookeeper概念

zookeeper是 apache hadoop 项目下的一个子项目,是一个树形目录服务

zookeeper 翻译过来就是动物园管理员,他是用来管 hadoop(大象)、hive(蜜蜂)、pig(小猪)的管理员。简称zk

hadoop: 存储海量数据和分析海量数据的工具

hive: 基于hadoop的一个数据仓库工具,用来进行数据提取、转化、加载

pig: 基于hadoop的大规模数据分析平台

zookeeper 是一个开源的,分布式应用程序的协调服务

zookeeper 提供的主要功能包括:

注册中心:比如dubbo的注册中心

分布式锁:比如卖电影票有好多入口:官网、猫眼、淘票票

配置管理:比如用来保存项目的各种配置信息(数据库连接信息);常用的配置中心:apollo(百度开源)、nacos(阿里开源)

2.zookeeper 命令操作

1.数据模型

zookeeper 是一个树形目录服务,其数据模型和unix的文件系统目录树很类似,拥有一个层次化结构。

这里面的每一个节点都被称为:znode,每个节点上都会保存自己的数据和节点信息。

节点可以拥有子节点,同时也允许少量(1mb)数据存储在该节点之下

节点可以分为四大类:

持久节点(persistent):创建后一直存在,直到主动删除此节点

临时节点(ephemeral):生命周期依赖于客户端会话,对应客户端会话失效后节点自动清除:-e

持久顺序节点(persistent_sequential) :持久顺序节点,创建后一直存在,直到主动删除此节点:-s

临时顺序节点(ephemeral_sequential) :临时节点在客户端会话失效后节点自动清:-es

2.服务端命令

启动 zookeeper 服务: ./zkserver.sh start

查看 zookeeper 服务状态: ./zkserver.sh status

停止 zookeeper 服务: ./zkserver.sh stop

重启 zookeeper 服务: ./zkserver.sh restart

3.客户端常用命令

连接zookeeper服务端

显示指定目录下节点 

 

创建根节点

获取节点

设置节点

创建子节点

删除单个节点

删除带有子节点的节点

查看命令帮助

4.创建临时节点和顺序节点

创建临时节点

创建顺序节点,zk会自动在节点路径后边添加序号

创建临时顺序节点

czxid:节点被创建的事务id

ctime: 创建时间

mzxid: 最后一次被更新的事务id

mtime: 修改时间

pzxid:子节点列表最后一次被更新的事务id

cversion:子节点的版本号

dataversion:数据版本号

aclversion:权限版本号

ephemeralowner:用于临时节点,代表临时节点的事务id,如果为持久节点则为0

datalength:节点存储的数据的长度

numchildren:当前节点的子节点个数 

查询节点详细信息

2..zookeeper javaapi 操作 

1.curator介绍

curator 是 apache zookeeper 的java客户端库,目标是简化 zookeeper 客户端的使用

常见的zookeeper java api :

原生java api

zkclient

curator

curator 最初是 netfix 研发的,后来捐献了 apache 基金会,目前是 apache 的顶级项目

官网:welcome to apache curator | apache curator

2.建立连接

创建项目curator-zk

pom.xml中添加curator和日志坐标 

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    </properties>
    <dependencies>
        <!--单元测试-->
        <dependency>
            <groupid>junit</groupid>
            <artifactid>junit</artifactid>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <!--curator-->
        <dependency>
            <groupid>org.apache.curator</groupid>
            <artifactid>curator-framework</artifactid>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupid>org.apache.curator</groupid>
            <artifactid>curator-recipes</artifactid>
            <version>4.0.0</version>
        </dependency>
        <!--日志-->
        <dependency>
            <groupid>org.slf4j</groupid>
            <artifactid>slf4j-api</artifactid>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupid>org.slf4j</groupid>
            <artifactid>slf4j-log4j12</artifactid>
            <version>1.7.21</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupid>org.apache.maven.plugins</groupid>
                <artifactid>maven-compiler-plugin</artifactid>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

日志配置文件:log4j.properties

log4j.rootlogger=off,stdout

log4j.appender.stdout = org.apache.log4j.consoleappender
log4j.appender.stdout.target = system.out
log4j.appender.stdout.layout = org.apache.log4j.patternlayout
log4j.appender.stdout.layout.conversionpattern = [%d{yyyy-mm-dd hh/:mm/:ss}]%-5p %c(line/:%l) %x-%m%n

在java测试包下创建com\curator包创建测试类curatortest

package com.curator;

import org.apache.curator.retrypolicy;
import org.apache.curator.framework.curatorframework;
import org.apache.curator.framework.curatorframeworkfactory;
import org.apache.curator.retry.exponentialbackoffretry;
import org.junit.test;

public class curatortest {
    /*
    * 建立连接
    */
    @test
    public void testconnect() {
        /*
         * connectstring         连接字符串。zk server 地址和端口
         * sessiontimeoutms      会话差事时间 单位ms
         * connectiontimeoutms   连接超时时间 单位ms
         * retrypolicy           重试策略
         */
        //重试策略
        retrypolicy retrypolicy = new exponentialbackoffretry(3000, 10);
        //第一种方式
        /*curatorframework client = curatorframeworkfactory.newclient("192.168.235.129:2181",
                60*1000,15*1000,retrypolicy);*/
        //常用第二种方式,更直观
        curatorframework client = curatorframeworkfactory.builder()
                .connectstring("192.168.235.129:2181")
                .sessiontimeoutms(60 * 1000)
                .connectiontimeoutms(15 * 1000)
                .retrypolicy(retrypolicy)
                .namespace("ljb")
                .build();
        //开启连接
        client.start();
    }

}

3.创建节点

@before:初始化方法(对于每一个测试方法都要执行一次)

@after:释放资源(对于每一个测试方法运行完后都要执行一次)

package com.curator;

import org.apache.curator.retrypolicy;
import org.apache.curator.framework.curatorframework;
import org.apache.curator.framework.curatorframeworkfactory;
import org.apache.curator.retry.exponentialbackoffretry;
import org.apache.zookeeper.createmode;
import org.junit.after;
import org.junit.before;
import org.junit.test;

public class curatortest {
    /*
    * 建立连接
    */
    private curatorframework client;
    @before
    public void testconnect() {
        /*
         * connectstring         连接字符串。zk server 地址和端口
         * sessiontimeoutms      会话差事时间 单位ms
         * connectiontimeoutms   连接超时时间 单位ms
         * retrypolicy           重试策略
         */
        //重试策略
        retrypolicy retrypolicy = new exponentialbackoffretry(3000, 10);
        //第一种方式
        /*curatorframework client = curatorframeworkfactory.newclient("192.168.235.129:2181",
                60*1000,15*1000,retrypolicy);*/
        //常用第二种方式,更直观
        client = curatorframeworkfactory.builder()
                .connectstring("192.168.235.129:2181")
                .sessiontimeoutms(60 * 1000)
                .connectiontimeoutms(15 * 1000)
                .retrypolicy(retrypolicy)
                .namespace("ljb")
                .build();
        //开启连接
        client.start();
    }

    /*
    * 创建节点:create 持久 临时 顺序 数据
    * 1.基本创建
    * 2.创建节点 带有数据
    * 3.设置节点的类型
    * 4.创建多级节点 /app1/p1
    */
    @test
    public void testcreate() throws exception {
        //1. 基本创建 :create().forpath("")
        //如果创建节点,没有指定数据,则默认将当前客户端的ip作为数据存储
        string path = client.create().forpath("/app1");
        system.out.println(path);
    }

    @test
    public void testcreate2() throws exception {
        //2. 创建节点 带有数据:create().forpath("",data)
        //节点默认类型:持久化
        string path = client.create().forpath("/app2", "hehe".getbytes());
        system.out.println(path);
    }

    @test
    public void testcreate3() throws exception {
        //3. 设置节点的类型:create().withmode().forpath("",data)
        //创建临时节点
        string path = client.create().withmode(createmode.ephemeral).forpath("/app3");
        system.out.println(path);
    }

    @test
    public void testcreate4() throws exception {
        //创建多级节点  /app1/p1 :create().creatingparentsifneeded().forpath("",data)
        //creatingparentsifneeded():如果父节点不存在,则创建父节点
        string path = client.create().creatingparentsifneeded().forpath("/app4/p1");
        system.out.println(path);
    }

    @after
    public void close() {
        if (client != null) {
            client.close();
        }
    }


}

4.查询节点

//====================get===============================
    /**
     * 查询节点:
     * 1. 查询数据:get: getdata().forpath()
     * 2. 查询子节点: ls: getchildren().forpath()
     * 3. 查询节点状态信息:ls -s:getdata().storingstatin(状态对象).forpath()
     */
    @test
    public void testget1() throws exception {
        //1. 查询数据:get
        byte[] data = client.getdata().forpath("/app1");
        system.out.println(new string(data));
    }
    @test
    public void testget2() throws exception {
        // 2. 查询子节点: ls
        list<string> path = client.getchildren().forpath("/");
        system.out.println(path);
    }
    @test
    public void testget3() throws exception {
        stat status = new stat();
        system.out.println(status);
        //3. 查询节点状态信息:ls -s
        // store status in ...
        client.getdata().storingstatin(status).forpath("/app1");
        system.out.println(status);
    }

5.修改节点 

    //=====================set==================
    /**
     * 修改数据
     * 1. 基本修改数据:setdata().forpath()
     * 2. 根据版本修改: setdata().withversion().forpath()
     * * version 是通过查询出来的。目的就是为了让其他客户端或者线程不干扰我。
     *
     * @throws exception
     */
    @test
    public void testset() throws exception {
        client.setdata().forpath("/app1", "ljb".getbytes());
    }

    @test
    public void testsetforversion() throws exception {
        stat status = new stat();
        //3. 查询节点状态信息:ls -s
        client.getdata().storingstatin(status).forpath("/app1");
        int version = status.getversion();//查询出来的 3
        system.out.println(version);
        client.setdata().withversion(version).forpath("/app1", "hehe".getbytes());
    }

6.删除结点

    //=================delete=================
    /**
     * 删除节点: delete deleteall
     * 1. 删除单个节点:delete().forpath("/app1");
     * 2. 删除带有子节点的节点:delete().deletingchildrenifneeded().forpath("/app1");
     * 3. 必须成功的删除:为了防止网络抖动。本质就是重试。  client.delete().guaranteed().forpath("/app2");
     * 4. 回调:inbackground
     */
    @test
    public void testdelete() throws exception {
        // 1. 删除单个节点
        client.delete().forpath("/app1");
    }
    @test
    public void testdelete2() throws exception {
        //2. 删除带有子节点的节点
        client.delete().deletingchildrenifneeded().forpath("/app4");
    }

    @test
    public void testdelete3() throws exception {
        //3. 必须成功的删除, 底层是自动重试
        client.delete().guaranteed().forpath("/app2");
    }

    @test
    public void testdelete4() throws exception {
        //4. 回调
        client.delete().guaranteed().inbackground(new backgroundcallback(){
            @override
            public void processresult(curatorframework client, curatorevent event) throws exception {
                system.out.println("我被删除了~");
                system.out.println(event);
            }
        }).forpath("/app1");
    }

完整代码 

package com.curator;

import org.apache.curator.retrypolicy;
import org.apache.curator.framework.curatorframework;
import org.apache.curator.framework.curatorframeworkfactory;
import org.apache.curator.framework.api.backgroundcallback;
import org.apache.curator.framework.api.curatorevent;
import org.apache.curator.retry.exponentialbackoffretry;
import org.apache.zookeeper.createmode;
import org.apache.zookeeper.data.stat;
import org.junit.after;
import org.junit.before;
import org.junit.test;

import java.util.list;

public class curatortest {
    /*
    * 建立连接
    */
    private curatorframework client;
    @before
    public void testconnect() {
        /*
         * connectstring         连接字符串。zk server 地址和端口
         * sessiontimeoutms      会话差事时间 单位ms
         * connectiontimeoutms   连接超时时间 单位ms
         * retrypolicy           重试策略
         */
        //重试策略
        retrypolicy retrypolicy = new exponentialbackoffretry(3000, 10);
        //第一种方式
        /*curatorframework client = curatorframeworkfactory.newclient("192.168.235.129:2181",
                60*1000,15*1000,retrypolicy);*/
        //常用第二种方式,更直观
        client = curatorframeworkfactory.builder()
                .connectstring("192.168.235.129:2181")
                .sessiontimeoutms(60 * 1000)
                .connectiontimeoutms(15 * 1000)
                .retrypolicy(retrypolicy)
                .namespace("ljb")
                .build();
        //开启连接
        client.start();
    }
//======================create=====================
    /*
    * 创建节点:create 持久 临时 顺序 数据
    * 1.基本创建
    * 2.创建节点 带有数据
    * 3.设置节点的类型
    * 4.创建多级节点 /app1/p1
    */
    @test
    public void testcreate() throws exception {
        //1. 基本创建 :create().forpath("")
        //如果创建节点,没有指定数据,则默认将当前客户端的ip作为数据存储
        string path = client.create().forpath("/app1");
        system.out.println(path);
    }

    @test
    public void testcreate2() throws exception {
        //2. 创建节点 带有数据:create().forpath("",data)
        //节点默认类型:持久化
        string path = client.create().forpath("/app2", "hehe".getbytes());
        system.out.println(path);
    }

    @test
    public void testcreate3() throws exception {
        //3. 设置节点的类型:create().withmode().forpath("",data)
        //创建临时节点
        string path = client.create().withmode(createmode.ephemeral).forpath("/app3");
        system.out.println(path);
    }

    @test
    public void testcreate4() throws exception {
        //创建多级节点  /app1/p1 :create().creatingparentsifneeded().forpath("",data)
        //creatingparentsifneeded():如果父节点不存在,则创建父节点
        string path = client.create().creatingparentsifneeded().forpath("/app4/p1");
        system.out.println(path);
    }
//====================get===============================
    /**
     * 查询节点:
     * 1. 查询数据:get: getdata().forpath()
     * 2. 查询子节点: ls: getchildren().forpath()
     * 3. 查询节点状态信息:ls -s:getdata().storingstatin(状态对象).forpath()
     */
    @test
    public void testget1() throws exception {
        //1. 查询数据:get
        byte[] data = client.getdata().forpath("/app1");
        system.out.println(new string(data));
    }
    @test
    public void testget2() throws exception {
        // 2. 查询子节点: ls
        list<string> path = client.getchildren().forpath("/");
        system.out.println(path);
    }
    @test
    public void testget3() throws exception {
        stat status = new stat();
        system.out.println(status);
        //3. 查询节点状态信息:ls -s
        // store status in ...
        client.getdata().storingstatin(status).forpath("/app1");
        system.out.println(status);
    }
    //=====================set==================

     /** 修改数据
     * 1. 基本修改数据:setdata().forpath()
     * 2. 根据版本修改: setdata().withversion().forpath()
     * * version 是通过查询出来的。目的就是为了让其他客户端或者线程不干扰我。
      */

    @test
    public void testset() throws exception {
        client.setdata().forpath("/app1", "ljb".getbytes());
    }

    @test
    public void testsetforversion() throws exception {
        stat status = new stat();
        //3. 查询节点状态信息:ls -s
        client.getdata().storingstatin(status).forpath("/app1");
        int version = status.getversion();//查询出来的 3
        system.out.println(version);
        client.setdata().withversion(version).forpath("/app1", "hehe".getbytes());
    }

    //=================delete=================
    /**
     * 删除节点: delete deleteall
     * 1. 删除单个节点:delete().forpath("/app1");
     * 2. 删除带有子节点的节点:delete().deletingchildrenifneeded().forpath("/app1");
     * 3. 必须成功的删除:为了防止网络抖动。本质就是重试。  client.delete().guaranteed().forpath("/app2");
     * 4. 回调:inbackground
     */
    @test
    public void testdelete() throws exception {
        // 1. 删除单个节点
        client.delete().forpath("/app1");
    }
    @test
    public void testdelete2() throws exception {
        //2. 删除带有子节点的节点
        client.delete().deletingchildrenifneeded().forpath("/app4");
    }

    @test
    public void testdelete3() throws exception {
        //3. 必须成功的删除, 底层是自动重试
        client.delete().guaranteed().forpath("/app2");
    }

    @test
    public void testdelete4() throws exception {
        //4. 回调
        client.delete().guaranteed().inbackground(new backgroundcallback(){
            @override
            public void processresult(curatorframework client, curatorevent event) throws exception {
                system.out.println("我被删除了~");
                system.out.println(event);
            }
        }).forpath("/app1");
    }

    @after
    public void close() {
        if (client != null) {
            client.close();
        }
    }
}

7.watch监听概念 

zookeeper 允许用户在指定节点上注册一些watcher,并且在一些特定事件触发的时候,zookeeper 服务端会将事件通知到感兴趣的客户端上去,该机制是 zookeeper 实现分布式协调服务的重要特性

zookeeper 中引入了watcher机制来实现了发布/订阅功能能,能够让多个订阅者同时监听某一个对象,当一个对象自身状态变化时,会通知所有订阅者

zookeeper 原生支持通过注册watcher来进行事件监听,但是其使用并不是特别方便,需要开发人员自己反复注册watcher,比较繁琐

curator引入了 cache 来实现对 zookeeper 服务端事件的监听

zookeeper提供了三种watcher:

nodecache : 只监听某一个特定的节点

pathchildrencache : 监控一个znode的子节点 

treecache : 可以监控整个树上的所有节点,类似于pathchildrencache和nodecache的组合

8.watch监听-nodecache

只监听某一个特定的节点

package com.curator;

import org.apache.curator.retrypolicy;
import org.apache.curator.framework.curatorframework;
import org.apache.curator.framework.curatorframeworkfactory;
import org.apache.curator.framework.recipes.cache.nodecache;
import org.apache.curator.framework.recipes.cache.nodecachelistener;
import org.apache.curator.retry.exponentialbackoffretry;
import org.junit.after;
import org.junit.before;
import org.junit.test;

public class curatorwatchertest {
    /*
     * 建立连接
     */
    private curatorframework client;
    @before
    public void testconnect() {
        /*
         * connectstring         连接字符串。zk server 地址和端口
         * sessiontimeoutms      会话差事时间 单位ms
         * connectiontimeoutms   连接超时时间 单位ms
         * retrypolicy           重试策略
         */
        //重试策略
        retrypolicy retrypolicy = new exponentialbackoffretry(3000, 10);
        //第一种方式
        /*curatorframework client = curatorframeworkfactory.newclient("192.168.235.129:2181",
                60*1000,15*1000,retrypolicy);*/
        //常用第二种方式,更直观
        client = curatorframeworkfactory.builder()
                .connectstring("192.168.235.129:2181")
                .sessiontimeoutms(60 * 1000)
                .connectiontimeoutms(15 * 1000)
                .retrypolicy(retrypolicy)
                .namespace("ljb")
                .build();
        //开启连接
        client.start();
    }
    @after
    public void close() {
        if (client != null) {
            client.close();
        }
    }

    /**
     * 演示 nodecache:给指定一个节点注册监听器
     */
    @test
    public void testnodecache() throws exception {
        //1. 创建nodecache对象
        nodecache nodecache = new nodecache(client,"/app1");
        //2. 注册监听
        nodecache.getlistenable().addlistener(new nodecachelistener() {
            @override
            public void nodechanged() throws exception {
                system.out.println("节点变化了~");
                //获取修改节点后的数据
                byte[] data = nodecache.getcurrentdata().getdata();
                system.out.println(new string(data));
            }
        });
        //3. 开启监听.如果设置为true,则开启监听是,加载缓冲数据
        nodecache.start(true);
        while (true){
        }
    }
}

9.watch监听-pathchildrencache

监控一个znode的子节点

package com.curator;

import org.apache.curator.retrypolicy;
import org.apache.curator.framework.curatorframework;
import org.apache.curator.framework.curatorframeworkfactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.exponentialbackoffretry;
import org.junit.after;
import org.junit.before;
import org.junit.test;

public class curatorwatchertest {
    /*
     * 建立连接
     */
    private curatorframework client;
    @before
    public void testconnect() {
        /*
         * connectstring         连接字符串。zk server 地址和端口
         * sessiontimeoutms      会话差事时间 单位ms
         * connectiontimeoutms   连接超时时间 单位ms
         * retrypolicy           重试策略
         */
        //重试策略
        retrypolicy retrypolicy = new exponentialbackoffretry(3000, 10);
        //第一种方式
        /*curatorframework client = curatorframeworkfactory.newclient("192.168.235.129:2181",
                60*1000,15*1000,retrypolicy);*/
        //常用第二种方式,更直观
        client = curatorframeworkfactory.builder()
                .connectstring("192.168.235.129:2181")
                .sessiontimeoutms(60 * 1000)
                .connectiontimeoutms(15 * 1000)
                .retrypolicy(retrypolicy)
                .namespace("ljb")
                .build();
        //开启连接
        client.start();
    }
    @after
    public void close() {
        if (client != null) {
            client.close();
        }
    }

    @test
    public void testpathchildrencache() throws exception {
        //1.创建监听对象
        pathchildrencache pathchildrencache = new pathchildrencache(client,"/app2",true);
        //2. 绑定监听器
        pathchildrencache.getlistenable().addlistener(new pathchildrencachelistener() {    			@override
        public void childevent(curatorframework client, pathchildrencacheevent event) throws exception {
            system.out.println("子节点变化了~");
            system.out.println(event);
            //监听子节点的数据变更,并且拿到变更后的数据
            //1.获取类型
            pathchildrencacheevent.type type = event.gettype();
            //2.判断类型是否是update
            if(type.equals(pathchildrencacheevent.type.child_updated)){
                system.out.println("数据变了!!!");
                byte[] data = event.getdata().getdata();
                system.out.println(new string(data));
            }
        }
        });
        //3. 开启
        pathchildrencache.start();
        while (true){
        }
    }
}

10.watch监听-treecache 

可以监控整个树上的所有节点,类似于pathchildrencache和nodecache的组合

package com.curator;

import org.apache.curator.retrypolicy;
import org.apache.curator.framework.curatorframework;
import org.apache.curator.framework.curatorframeworkfactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.exponentialbackoffretry;
import org.junit.after;
import org.junit.before;
import org.junit.test;

public class curatorwatchertest {
    /*
     * 建立连接
     */
    private curatorframework client;
    @before
    public void testconnect() {
        /*
         * connectstring         连接字符串。zk server 地址和端口
         * sessiontimeoutms      会话差事时间 单位ms
         * connectiontimeoutms   连接超时时间 单位ms
         * retrypolicy           重试策略
         */
        //重试策略
        retrypolicy retrypolicy = new exponentialbackoffretry(3000, 10);
        //第一种方式
        /*curatorframework client = curatorframeworkfactory.newclient("192.168.235.129:2181",
                60*1000,15*1000,retrypolicy);*/
        //常用第二种方式,更直观
        client = curatorframeworkfactory.builder()
                .connectstring("192.168.235.129:2181")
                .sessiontimeoutms(60 * 1000)
                .connectiontimeoutms(15 * 1000)
                .retrypolicy(retrypolicy)
                .namespace("ljb")
                .build();
        //开启连接
        client.start();
    }
    @after
    public void close() {
        if (client != null) {
            client.close();
        }
    }

    @test
    public void testtreecache() throws exception {
        //1. 创建监听器
        treecache treecache = new treecache(client,"/app2");
        //2. 注册监听
        treecache.getlistenable().addlistener(new treecachelistener() {
            @override
            public void childevent(curatorframework client, treecacheevent event) throws exception {
                system.out.println("节点变化了");
                system.out.println(event);
            }
        });
        //3. 开启
        treecache.start();
        while (true){
        }
    }
}

3.分布式锁

1.概述

在我们进行单机应用开发,涉及并发同步的时候,我们往往采用synchronized(同步)或者lock的方式来解决多线程间的代码同步问题,这时多线程的运行都是在同一个jvm之下,没有任何问题

但当我们的应用是分布式集群工作的情况下,属于多jvm下的工作环境,跨jvm之间已经无法通过多线程的锁解决同步问题

那么就需要一种更加高级的锁机制,来处理这种跨机器的进程之间的数据同步问题——这就是分布式锁

2.zookeeper分布式锁原理

核心思想:当客户端要获取锁,则创建节点,使用完锁,则删除该节点 

1.客户端获取锁时,在lock节点下创建临时顺序节点。

2.然后获取lock下面的所有子节点,客户端获取到所有的子节点之后,如果发现自己创建的子节点序号最小,那么就认为该客户端获取到了锁。使用完锁后,将该节点删除。

3.如果发现自己创建的节点并非lock所有子节点中最小的,说明自己还没有获取到锁,此时客户端需要找到比自己小的那个节点,同时对其注册事件监听器,监听删除事件。

4.如果发现比自己小的那个节点被删除,则客户端的watcher会收到相应通知,此时再次判断自己创建的节点是否是lock子节点中序号最小的;如果是则获取到了锁,如果不是则重复以上步骤继续获取到比自己小的一个节点并注册监听

为什么创建的是临时顺序节点: 如果是持久化结点,如果获取锁的节点宕机,锁就不会被释放,如果是临时的锁就会被自动释放。是顺序节点是因为要找最小的节点所以要排个顺序

3.模拟12306售票案例

在curator中有五种锁方案:

interprocesssemaphoremutex:分布式排它锁(非可重入锁)

interprocessmutex:分布式可重入排它锁

interprocessreadwritelock:分布式读写锁

interprocessmultilock:将多个锁作为单个实体管理的容器

interprocesssemaphorev2:共享信号量

创建线程进行加锁设置

package com.curator;

import org.apache.curator.retrypolicy;
import org.apache.curator.framework.curatorframework;
import org.apache.curator.framework.curatorframeworkfactory;
import org.apache.curator.framework.recipes.locks.interprocessmutex;
import org.apache.curator.retry.exponentialbackoffretry;

import java.util.concurrent.timeunit;

public class ticket12306 implements runnable{
    private int tickets = 10;//数据库的票数
    private interprocessmutex lock ;
    //在构造方法中创建连接,并且初始化锁
    public ticket12306() {
        //重试策略
        retrypolicy retrypolicy = new exponentialbackoffretry(3000, 10);
        //2.第二种方式
        //curatorframeworkfactory.builder();
        curatorframework client = curatorframeworkfactory.builder()
                .connectstring("192.168.235.129:2181")
                .sessiontimeoutms(60 * 1000)
                .connectiontimeoutms(15 * 1000)
                .retrypolicy(retrypolicy)
                .build();

        //开启连接
        client.start();
        try {
            if (client.checkexists().forpath("/lock") != null) {
                //删除之前测试遗留的/lock节点
                client.delete().deletingchildrenifneeded().forpath("/lock");
            }
        } catch (exception e) {
            e.printstacktrace();
        }
        lock = new interprocessmutex(client, "/lock");
    }

    @override
    public void run() {
        while(true){
            //获取锁
            try {
                lock.acquire(3, timeunit.seconds);//时间与时间单位
                if(tickets > 0){
                    system.out.println(thread.currentthread()+":"+tickets);
                    thread.sleep(100);
                    tickets--;
                }
            } catch (exception e) {
                e.printstacktrace();
            }finally {
                //释放锁
                try {
                    lock.release();
                } catch (exception e) {
                    e.printstacktrace();
                }
            }
        }
    }
}

测试

package com.curator;

public class locktest {
    public static void main(string[] args) {
        ticket12306 ticket12306 = new ticket12306();
        //创建客户端
        thread t1 = new thread(ticket12306,"携程");
        thread t2 = new thread(ticket12306,"飞猪");
        t1.start();
        t2.start();
    }
}

 

4.zookeeper 集群搭建 

1.zookeeper集群概述

leader选举:

serverid:服务器id

比如有三台服务器,编号分别是1,2,3

编号越大在选择算法中的权重越大

zxid:数据id

服务器中存放的最大数据id,值越大说明数据越新,在选举算法中数据越新权重越大

在leader选举的过程中,如果某台zookeeper获得了超过半数的选票,则此zookeeper就可以成为leader了

2.集群搭建

搭建要求

真实的集群是需要部署在不同的服务器上的,但是在我们测试时同时启动很多个虚拟机内存会吃不消,所以我们通常会搭建伪集群,也就是把所有的服务都搭建在一台虚拟机上,用端口进行区分。

我们这里要求搭建一个三个节点的zookeeper集群(伪集群)

3.搭建准备

建立/usr/local/zookeeper-cluster目录,将解压后的zookeeper复制到以下三个目录

创建data目录 ,并且将 conf下zoo_sample.cfg 文件改名为 zoo.cfg

配置每一个zookeeper 的datadir 和 clientport 分别为2181 2182 2183

4.配置集群

在每个zookeeper的 data 目录下创建一个 myid 文件,内容分别是1、2、3 。这个文件就是记录每个服务器的id

在每一个zookeeper 的 zoo.cfg配置客户端访问端口(clientport)和集群服务器ip列表

注:server.服务器id=服务器ip地址:服务器之间通信端口:服务器之间投票选举端口

5.启动集群

启动集群就是分别启动每个实例

启动后查询一下每个实例的运行状态

先查询第一个服务:mode为follower表示是跟随者(从)

再查询第二个服务:mod 为leader表示是领导者(主)

查询第三个为跟随者(从)

6.模拟集群异常 

首先我们先测试如果是从服务器挂掉,会怎么样

把3号服务器停掉,观察1号和2号,发现状态并没有变化

由此得出结论,3个节点的集群,从服务器挂掉,集群正常

再把1号服务器(从服务器)也停掉,查看2号(主服务器)的状态,发现已经停止运行了

3个节点的集群,2个从服务器都挂掉,主服务器也无法运行。因为可运行的机器没有超过集群总数量的半数

我们再次把1号服务器启动起来,发现2号服务器又开始正常工作了。而且依然是领导者

我们把3号服务器也启动起来,把2号服务器停掉,停掉后观察1号和3号的状态

发现新的leader产生了

当集群中的主服务器挂了,集群中的其他服务器会自动进行选举状态,然后产生新得leader

我们再次测试,当我们把2号服务器重新启动起来启动后,会发生什么?2号服务器会再次成为新的领导吗

我们会发现,2号服务器启动后依然是跟随者(从服务器),3号服务器依然是领导者(主服务器),没有撼动3号服务器的领导地位

当领导者产生后,再次有新服务器加入集群,不会影响到现任领导者

7.zookeeper 集群核心理论

在zookeeper集群服务中有三个角色:

leader 领导者 :

1.处理事务请求(增删改操作)

2.集群内部各服务器的调度者

follower 跟随者 :

1.处理客户端非事务请求(查询操作),转发事务请求给leader服务器

2.参与leader选举投票

observer 观察者:

处理客户端非事务请求(查询操作),转发事务请求给leader服务器

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com