Javaで[シリーズ] 2 ZooKeeperのZooKeeperのAPI呼び出し

温馨提示:ここで私は再び少し要件を言及し、私はあなたが見に慣れることを願って公式文書の意味を表現する基本的な文書を理解することができ、文書が英語であるが、しかし、言葉は比較的簡単です。魚へのティーチ彼をより魚に彼を教える理由私たちはすべてを理解し信じている、と希望、この谷サルのZooKeeperシリーズを通して、私たちは始めるように、おなじみの、習熟度のZooKeeperを最優先した後。

我々は導入以前ではビルドにZooKeeperのスタンドアローン版、擬似クラスタ環境をコマンドラインから、ノード、削除、更新、アクセスノードテスト情報を作成しました。飼育係の目的は、単純な、複雑なクライアントの連携機能を構築するための効率的なコアAPI、我々はこれらのCRUD機能を実現するためのZooKeeperが提供するJava APIのインタフェースを使用して、このいずれかを提供することです。

1はじめに

org.apache.zookeeper.ZookeeperでメインクラスのZooKeeperクライアントです公式文書が明確に記述されています(これは、のZooKeeperのメインクラスであるクライアントライブラリ。)。

これは、ZooKeeperのクライアントライブラリのメインクラスです。ZooKeeperのサービスを使用するには、アプリケーションが最初のZooKeeperクラスのオブジェクトをインスタンス化する必要があります。すべての反復はZooKeeperのクラスのメソッドを呼び出すことによって行われます。特に断りのない限り、このクラスのメソッドは、スレッドセーフです。
サーバーへの接続が確立されると、セッションIDは、クライアントに割り当てられています。クライアントは、有効なセッションを維持するために定期的にサーバにハートビートを送信します。

使用するのZooKeeperのインスタンスを作成org.apache.zookeeper.Zookeeperする方法では、公式文書が具体的に述べられていないことを指摘し、それから、メソッドのZooKeeperのクラスがある线程安全の。ZooKeeperのクライアントがサービスに接続するために、セッションID(セッションID)を割り当てますクライアントは、セッションを維持するために、クライアントとサーバが有効心拍になります。

org.apache.zookeeper.Zookeeper非常に多くの方法では、私は、CRUDのほんの数の列を、それらを表示されません。
|メソッド、|説明|
| - | - |
|作成(文字列のパス、バイト[]データ、リスト ACL、CreateMode createMode)|作成します (指定したパスを持つノードを|指定したパスのノードを作成するため)。
|を作成(文字列のパス、バイト[]データ、リスト ACL、CreateMode createMode、AsyncCallback.Create2CallbackのCB、オブジェクトCTX)| 作成の非同期バージョン(异步形式创建)。|
| (文字列のパス、バイト[]のデータを作成し、リスト ACL、CreateMode createMode、スタットスタット) |指定されたパスを持つノードを作成し、そのノードの統計を返します( )指定されたパスとリターン・ノードのステータス情報でノードを作成します。|
|削除(文字列のパス、int型版)|削除するノードで、 |指定されたパスで(削除ノードは、パスを指定)。
|削除(文字列のパス、int型バージョン、AsyncCallback.VoidCallbackのCB、オブジェクトCTX)|削除の非同期バージョン(非同期削除ノードは、パスを指定)で|。
|文字列(EXISTSパス、ブール腕時計)|リターン (指定したパスのノードのSTAT )指定されたパスのノード状態情報のを|。
| GetChildrenメソッド(文字列のパス、ブールウォッチ)|リターン与えられたパスのノードの子のリスト。(指定したパスのすべての子ノードの状態情報の)|
|のgetData(文字列のパス、ブールウォッチ、スタットSTAT)|。リターンデータと指定されたパスのノードデータとステータス情報の指定したパスのノードのSTAT( )|
| SetDataメソッド(文字列パス、バイト[]データ、INTバージョン)|セットデータ指定されたパスのノードのようなノードが存在し、指定されたバージョンである場合は-1、それは与えられたバージョンは、(ノードのバージョンに一致する場合。ノードに指定されたパス()は、任意のノードのバージョンと一致し、そのようなバージョン-1、すべてのバージョンのために、すなわち、設定値)として、バージョンの新しい値を設定|

2、テスト環境

ここでは、新しいブート春の新しい春のブートプロジェクトをテストするためのプロジェクトは、単純なプロセスであり、またここでの焦点は、導入されていません。

プロジェクトは、次の2つのパッケージには、追加のテストが必要になります導入されました。

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.5.2</version>
        </dependency>

3 APIテスト

完全なテストコードを次のように:

/**
 *  简单测试示例
 * @author 猿人谷
 * @date 2019/12/16
 */
public class ZooKeeperDemo {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperDemo.class);

    private static final int SESSION_TIME_OUT = 10000;
    // ZooKeeper服务的地址,如为集群,多个地址用逗号分隔
    private static final String CONNECT_STRING = "127.0.0.1:2181";
    private static final String ZNODE_PATH = "/zk_demo";
    private static final String ZNODE_PATH_PARENT = "/app1";
    private static final String ZNODE_PATH_CHILDREN = "/app1/app1_1";

    private ZooKeeper zk = null;

    @Before
    public void init() throws IOException {
        zk = new ZooKeeper(CONNECT_STRING, SESSION_TIME_OUT, new Watcher(){
            @Override
            public void process(WatchedEvent event) {
                System.out.println("已经触发了" + event.getType() + "事件!");
            }
        });

    }

    @Test
    public void testCreate() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH, "anna2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void testCreateParentZnode() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH_PARENT, "anna2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void testCreateChildrenZnode() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH_CHILDREN, "anna2020".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void testGet() throws KeeperException, InterruptedException {
        byte[] data1 = zk.getData(ZNODE_PATH, false, null);
        byte[] data2 = zk.getData(ZNODE_PATH_PARENT, false, null);
        byte[] data3 = zk.getData(ZNODE_PATH_CHILDREN, false, null);
        LOGGER.info("{}的信息:{}", ZNODE_PATH, new String(data1) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_PARENT, new String(data2) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_CHILDREN, new String(data3) );
    }

    /**
     *  删除
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testDelete() throws KeeperException, InterruptedException {
        // 指定要删除的版本,-1表示删除所有版本
        zk.delete(ZNODE_PATH, -1);
    }

    /**
     *  删除含有子节点
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testDeleteHasChildrenZnode() throws KeeperException, InterruptedException {
        // 指定要删除的版本,-1表示删除所有版本
        zk.delete(ZNODE_PATH_PARENT, -1);
    }

    @Test
    public void testSet() throws KeeperException, InterruptedException {
        Stat stat = zk.setData(ZNODE_PATH, "yuanrengu".getBytes(), -1);
        LOGGER.info(stat.toString());
    }

}

上記に便利な@Before以下で簡単に説明:

  • @BeforeClass - 任意のパブリック静的な無効方法は、クラスで実行する前に実行表し
  • @AfterClass - 任意のパブリック静的な無効方法は、クラスで実行した後に行う表し
  • @Before - どんなます。public voidメソッドがマークされ、実行@Test注釈を使用する前に実行表し
  • @After - マーク@Testコメントを使用して実行ます。public voidいずれかの方法の後に実行を表し
  • @Test - 注釈ラベルを使用します。public void方法は、試験方法として表現されます

場合SESSION_TIME_OUTの時間が短すぎる設定されている、それはクライアントAPI例外で報告されますorg.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /zk_demo次のエラーメッセージを完了します。

09:33:52.139 [main-SendThread(106.12.111.172:2181)] DEBUG org.apache.zookeeper.ClientCnxnSocketNIO - Ignoring exception during shutdown input
java.net.SocketException: Socket is not connected
    at sun.nio.ch.Net.translateToSocketException(Net.java:123)
    at sun.nio.ch.Net.translateException(Net.java:157)
    at sun.nio.ch.Net.translateException(Net.java:163)
    at sun.nio.ch.SocketAdaptor.shutdownInput(SocketAdaptor.java:401)
    at org.apache.zookeeper.ClientCnxnSocketNIO.cleanup(ClientCnxnSocketNIO.java:198)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanup(ClientCnxn.java:1338)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanAndNotifyState(ClientCnxn.java:1276)
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1254)
Caused by: java.nio.channels.NotYetConnectedException: null
    at sun.nio.ch.SocketChannelImpl.shutdownInput(SocketChannelImpl.java:782)
    at sun.nio.ch.SocketAdaptor.shutdownInput(SocketAdaptor.java:399)
    ... 4 common frames omitted
09:33:52.140 [main-SendThread(106.12.111.172:2181)] DEBUG org.apache.zookeeper.ClientCnxnSocketNIO - Ignoring exception during shutdown output
java.net.SocketException: Socket is not connected
    at sun.nio.ch.Net.translateToSocketException(Net.java:123)
    at sun.nio.ch.Net.translateException(Net.java:157)
    at sun.nio.ch.Net.translateException(Net.java:163)
    at sun.nio.ch.SocketAdaptor.shutdownOutput(SocketAdaptor.java:409)
    at org.apache.zookeeper.ClientCnxnSocketNIO.cleanup(ClientCnxnSocketNIO.java:205)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanup(ClientCnxn.java:1338)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanAndNotifyState(ClientCnxn.java:1276)
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1254)
Caused by: java.nio.channels.NotYetConnectedException: null
    at sun.nio.ch.SocketChannelImpl.shutdownOutput(SocketChannelImpl.java:799)
    at sun.nio.ch.SocketAdaptor.shutdownOutput(SocketAdaptor.java:407)
    ... 4 common frames omitted

org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /zk_demo

    at org.apache.zookeeper.KeeperException.create(KeeperException.java:102)
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
    at org.apache.zookeeper.ZooKeeper.getData(ZooKeeper.java:2131)
    at org.apache.zookeeper.ZooKeeper.getData(ZooKeeper.java:2160)
    at com.yuanrengu.demo.ZooKeeperDemo.testGet(ZooKeeperDemo.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Disconnected from the target VM, address: '127.0.0.1:60454', transport: 'socket'

Process finished with exit code -1

最初の考えでは、それは、ZooKeeperのサービスまたはサービスを展開して問題だったSESSION_TIME_OUTは= 2000ことが判明チェック、デバッグデバッグで確認後に起動しませんでした。値は10000は、もはやが与えられていないされているに変更し、小さすぎます。

SESSION_TIME_OUT市会话超时时间飼育係、時間ハートビートを超えた場合に、あるノードが障害であると考えられます。したがって、この値が小さい飼育係は、接続を作成するための時間を持っていた飼育係作成時間、超える場合、セッション時間が来ている、したがって、例外はノード障害を投げていると考えました。

3.1新

public String create(String path,
                     byte[] data,
                     List<ACL> acl,
                     CreateMode createMode)
              throws KeeperException,
                     InterruptedException
                     
Create a node with the given path. The node data will be the given data, and node acl will be the given acl.
The flags argument specifies whether the created node will be ephemeral or not.

An ephemeral node will be removed by the ZooKeeper automatically when the session associated with the creation of the node expires.

The flags argument can also specify to create a sequential node. The actual path name of a sequential node will be the given path plus a suffix "i" where i is the current sequential number of the node. The sequence number is always fixed length of 10 digits, 0 padded. Once such a node is created, the sequential number will be incremented by one.

If a node with the same actual path already exists in the ZooKeeper, a KeeperException with error code KeeperException.NodeExists will be thrown. Note that since a different actual path is used for each invocation of creating sequential node with the same path argument, the call will never throw "file exists" KeeperException.

If the parent node does not exist in the ZooKeeper, a KeeperException with error code KeeperException.NoNode will be thrown.

An ephemeral node cannot have children. If the parent node of the given path is ephemeral, a KeeperException with error code KeeperException.NoChildrenForEphemerals will be thrown.

This operation, if successful, will trigger all the watches left on the node of the given path by exists and getData API calls, and the watches left on the parent node by getChildren API calls.

If a node is created successfully, the ZooKeeper server will trigger the watches on the path left by exists calls, and the watches on the parent of the node by getChildren calls.

The maximum allowable size of the data array is 1 MB (1,048,576 bytes). Arrays larger than this will cause a KeeperExecption to be thrown.

Parameters:
path - the path for the node
data - the initial data for the node
acl - the acl for the node
createMode - specifying whether the node to be created is ephemeral and/or sequential
Returns:
the actual path of the created node
Throws:
KeeperException - if the server returns a non-zero error code
KeeperException.InvalidACLException - if the ACL is invalid, null, or empty
InterruptedException - if the transaction is interrupted
IllegalArgumentException - if an invalid path is specified

話は安いです。私のコードを表示します。ここでは、直接、公式文書に、BBブラインドされていません。公式ドキュメントを理解し、非常に明確に説明(とやや長いったらしい感)することは非常に簡単ではありませんか?

ここでは、ドキュメントのいくつかの重要なポイントで、単純な列

  1. 指定されたパスとノード作成フォーム、そのような一時的なノードとして、永続的なノードのノードとして指定することができます。
    ここで言うのもとCreateMode、当社は、ZooKeeperのノード(永続的、一時的、持続的なため、一時的な順序)の唯一の4つの形式は、実際には、そこにある、ドキュメントを参照してくださいと言うかもしれ7种形。
public enum CreateMode {
   PERSISTENT(0, false, false, false, false),
   PERSISTENT_SEQUENTIAL(2, false, true, false, false),
   EPHEMERAL(1, true, false, false, false),
   EPHEMERAL_SEQUENTIAL(3, true, true, false, false),
   CONTAINER(4, false, false, true, false),
   PERSISTENT_WITH_TTL(5, false, false, false, true),
   PERSISTENT_SEQUENTIAL_WITH_TTL(6, false, true, false, true);
}
  • PERSISTENT:(永久ノードとも呼ばれる)永続的なノードは、自動的にセッションの終わりで削除されません。
  • PERSISTENT_SEQUENTIAL:持続的なノードの単調に増加して、自動的にセッションの最後に削除されません。
  • エフェメラル:一時的なノードが自動的にセッションの終わりに削除されます。
  • EPHEMERAL_SEQUENTIAL:単調に増加する番号の一時的なノードは、自動的にセッションの終わりに削除されます。
  • CONTAINER:任意の子ノードノードコンテナが存在しない場合にリーダー、ロックやその他の特別な目的のためのコンテナノードは、コンテナが候補ノードサーバはいつか将来的に削除されます。
  • PERSISTENT_WITH_TTL:TTL(生存時間、生存期間)との永続的なノード、ノードは時間のTTL以内に更新され、子を持たないされていない、それは自動的に削除されます。
  • PERSISTENT_SEQUENTIAL_WITH_TTL:TTL(生存時間、生存期間)と単調にノード数の増加を持続して、ノードが時間のTTL以内に更新され、子を持たないされていない、それは自動的に削除されます。
  1. ノードの命令パスとバージョンがすでに存在している場合、それはKeeperException例外がスローされます。
  2. 临时节点不能有子节点あなたはノードスローKeeperException一時的な例外に子ノードを作成した場合。
  3. ライフサイクルの一時的なノードは、クライアント・セッションに関連付けられています。クライアント・セッションが(クライアントと飼育係必ずしも切断されたセッションの有効期限が切れる)が経過すると、クライアントは、すべての一時的なノードが削除されます作成されます
  4. byte[] data允许的最大数据量为1MB(1,048,576 bytes)もしそうなら、あなたはKeeperExecptionをスローします。

ノードを作成するコードを実行します。

    @Test
    public void testCreate() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH, "anna2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

あなたはノードを経て得られた成功したログ情報を作成することができます。

DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x101402626bb000b, packet:: clientPath:null serverPath:null finished:false header:: 1,1  replyHeader:: 1,12884901937,0  request:: '/zk_demo,#616e6e6132303139,v{s{31,s{'world,'anyone}}},0  response:: '/zk_demo

ビューへのサービス側では、成功を作成/ zk_demoノード:

[zk: 127.0.0.1:2181(CONNECTED) 21] ls /
[zookeeper, zk_demo]
[zk: 127.0.0.1:2181(CONNECTED) 22] stat /zk_demo
cZxid = 0x300000031
ctime = Tue Dec 17 12:52:50 CST 2019
mZxid = 0x300000031
mtime = Tue Dec 17 12:52:50 CST 2019
pZxid = 0x300000031
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 8
numChildren = 0

3.2を取得します

public byte[] getData(String path,
                      boolean watch,
                      Stat stat)
               throws KeeperException,
                      InterruptedException

Return the data and the stat of the node of the given path.
If the watch is true and the call is successful (no exception is thrown), a watch will be left on the node with the given path. The watch will be triggered by a successful operation that sets data on the node, or deletes the node.

A KeeperException with error code KeeperException.NoNode will be thrown if no node with the given path exists.

Parameters:
path - the given path
watch - whether need to watch this node
stat - the stat of the node
Returns:
the data of the node
Throws:
KeeperException - If the server signals an error with a non-zero error code
InterruptedException - If the server transaction is interrupted.

指定したパスが存在しない場合KeeperException.NoNodeノードが例外をスローします。

実行します。

    @Test
    public void testGet() throws KeeperException, InterruptedException {
        byte[] data1 = zk.getData(ZNODE_PATH, false, null);
        byte[] data2 = zk.getData(ZNODE_PATH_PARENT, false, null);
        byte[] data3 = zk.getData(ZNODE_PATH_CHILDREN, false, null);
        LOGGER.info("{}的信息:{}", ZNODE_PATH, new String(data1) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_PARENT, new String(data2) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_CHILDREN, new String(data3) );
    }

結果:

13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /zk_demo的信息:anna2019
13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1的信息:anna2019
13:51:00.289 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1/app1_1的信息:anna2020

3.3アップデート

public Stat setData(String path,
                    byte[] data,
                    int version)
             throws KeeperException,
                    InterruptedException
                    
Set the data for the node of the given path if such a node exists and the given version matches the version of the node (if the given version is -1, it matches any node's versions). Return the stat of the node.
This operation, if successful, will trigger all the watches on the node of the given path left by getData calls.

A KeeperException with error code KeeperException.NoNode will be thrown if no node with the given path exists.

A KeeperException with error code KeeperException.BadVersion will be thrown if the given version does not match the node's version.

The maximum allowable size of the data array is 1 MB (1,048,576 bytes). Arrays larger than this will cause a KeeperException to be thrown.

Parameters:
path - the path of the node
data - the data to set
version - the expected matching version
Returns:
the state of the node
Throws:
InterruptedException - If the server transaction is interrupted.
KeeperException - If the server signals an error with a non-zero error code.
IllegalArgumentException - if an invalid path is specified

主な次の点に注意してください

  1. バージョンは-1、それは指定されたパスの適応ノードのすべてのバージョンを意味します。
  2. 存在しないノード指定したパスがスローされます場合はKeeperException.NoNodeが異常、ノードが反転、バージョンが渡されていないKeeperException.BadVersionの例外を。
  3. byte[] data允许的最大数据量为1MB(1,048,576 bytes)もしそうなら、あなたはKeeperExecptionをスローします。

実行します。

    @Test
    public void testGet() throws KeeperException, InterruptedException {
        byte[] data1 = zk.getData(ZNODE_PATH, false, null);
        byte[] data2 = zk.getData(ZNODE_PATH_PARENT, false, null);
        byte[] data3 = zk.getData(ZNODE_PATH_CHILDREN, false, null);
        LOGGER.info("{}的信息:{}", ZNODE_PATH, new String(data1) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_PARENT, new String(data2) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_CHILDREN, new String(data3) );
    }

結果は以下の通りであります:

13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /zk_demo的信息:anna2019
13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1的信息:anna2019
13:51:00.289 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1/app1_1的信息:anna2020

3.4削除

public void delete(String path,
                   int version)
            throws InterruptedException,
                   KeeperException
                   
Delete the node with the given path. The call will succeed if such a node exists, and the given version matches the node's version (if the given version is -1, it matches any node's versions).
A KeeperException with error code KeeperException.NoNode will be thrown if the nodes does not exist.

A KeeperException with error code KeeperException.BadVersion will be thrown if the given version does not match the node's version.

A KeeperException with error code KeeperException.NotEmpty will be thrown if the node has children.

This operation, if successful, will trigger all the watches on the node of the given path left by exists API calls, and the watches on the parent node left by getChildren API calls.

Parameters:
path - the path of the node to be deleted.
version - the expected node version.
Throws:
InterruptedException - IF the server transaction is interrupted
KeeperException - If the server signals an error with a non-zero return code.
IllegalArgumentException - if an invalid path is specified

ノードは、ノートにはいくつかのポイントがある、操作の削除ノードを子ノードが含まれる場合があります。

  1. バージョンは-1、それは指定されたパスの適応ノードのすべてのバージョンを意味します。
  2. ノード指定したパスは、例外がスローされますKeeperException.NoNode存在しない場合、ノードはKeeperException.BadVersion例外を反転、バージョンが渡されていません。
  3. 如果节点含有子节点,删除父节点(parent node)时会抛KeeperException.NotEmpty异常。

/ App1のは、私たちが次の削除操作を行い、子ノードがあります。

    /**
     *  删除含有子节点的父节点
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testDeleteHasChildrenZnode() throws KeeperException, InterruptedException {
        // 指定要删除的版本,-1表示删除所有版本
        zk.delete(ZNODE_PATH_PARENT, -1);
    }

あなたはログを見ることができます:

org.apache.zookeeper.KeeperException$NotEmptyException: KeeperErrorCode = Directory not empty for /app1

    at org.apache.zookeeper.KeeperException.create(KeeperException.java:132)
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
    at org.apache.zookeeper.ZooKeeper.delete(ZooKeeper.java:1793)
    at com.yuanrengu.demo.ZooKeeperDemo.testDeleteHasChildrenZnode(ZooKeeperDemo.java:89)

4まとめ

私たちは、ノードの追加、削除、変更、テストを実現の上、後の章では、このような分散型ロック、コンフィギュレーション・センターの実装として、より多くの楽しい使い方があります。

上記の分析に基づいて、ノートにいくつかのポイントを要約したものです。

  1. ノードが持っています7种形式
  • PERSISTENT:(永久ノードとも呼ばれる)永続的なノードは、自動的にセッションの終わりで削除されません。
  • PERSISTENT_SEQUENTIAL:持続的なノードの単調に増加して、自動的にセッションの最後に削除されません。
  • エフェメラル:一時的なノードが自動的にセッションの終わりに削除されます。
  • EPHEMERAL_SEQUENTIAL:単調に増加する番号の一時的なノードは、自動的にセッションの終わりに削除されます。
  • CONTAINER:任意の子ノードノードコンテナが存在しない場合にリーダー、ロックやその他の特別な目的のためのコンテナノードは、コンテナが候補ノードサーバはいつか将来的に削除されます。
  • PERSISTENT_WITH_TTL:TTL(生存時間、生存期間)との永続的なノード、ノードは時間のTTL以内に更新され、子を持たないされていない、それは自動的に削除されます。
  • PERSISTENT_SEQUENTIAL_WITH_TTL:TTL(生存時間、生存期間)と単調にノード数の増加を持続して、ノードが時間のTTL以内に更新され、子を持たないされていない、それは自動的に削除されます。
  1. 一時的なノードが子ノードを持つことはできませんあなたはノードスローKeeperException一時的な例外に子ノードを作成した場合。
  2. ライフサイクルの一時的なノードは、クライアント・セッションに関連付けられています。クライアント・セッションが(クライアントと飼育係必ずしも切断されたセッションの有効期限が切れる)が経過すると、クライアントは、すべての一時的なノードが削除されます作成されます
  3. byte[] data允许的最大数据量为1MB(1,048,576 bytes)

おすすめ

転載: www.cnblogs.com/heyonggang/p/12058313.html