ZooKeeper应用之命名空间

命名服务
点击这里查看命名空间讲解

  • pom依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<properties>
<slf4j.version>1.7.5</slf4j.version>
<zookeeper.version>3.4.6</zookeeper.version>
<zkclient.version>0.2-SNAPSHOT</zkclient.version>
</properties>


<dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>${zkclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
  • ZK客户端类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    package org.zk.naming;

    import org.apache.zookeeper.*;
    import org.apache.zookeeper.data.ACL;
    import org.apache.zookeeper.data.Stat;

    import java.io.IOException;
    import java.util.List;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.atomic.AtomicInteger;

    /**
    * @auth zhengzhi.ren
    * @date 2015/7/24.
    */

    public class ZKClient {

    private final String rootNode;

    private final String serviceNode;

    private final String clazz;

    private final String businessNode;

    private final String hostNode;

    protected static ZooKeeper zkConn = null;

    private String host = "127.0.0.1:2181";

    private int timeout = 500000;

    public ZKClient(String rootNode, String serviceNode, String clazz, String businessNode, String hostNode) {
    this.rootNode = rootNode;
    this.serviceNode = this.rootNode + serviceNode;
    this.clazz = clazz;
    this.businessNode = this.serviceNode + businessNode;
    this.hostNode = this.businessNode + hostNode;
    }

    /**
    * get zk connection
    */

    public void connect() {
    try {
    CountDownLatch semaphore = new CountDownLatch(1);
    zkConn = new ZooKeeper(host, timeout, new ConnectWatcher(semaphore));
    semaphore.await();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    /**
    * create node
    */

    public void createNode() {
    connect();
    if (zkConn == null) {
    System.out.println("Warning, Get ZK connection failure!");
    }
    try {
    boolean result = create(rootNode, rootNode, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new CreateDubboCallback(), "create service node");
    if (!result) {
    result = create(serviceNode, serviceNode, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new CreateServiceCallback(), "create service node");
    }
    if (!result) {
    result = create(businessNode, businessNode, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new CreateProviderCallback(), "create provider node");
    }
    if (!result) {
    create(hostNode, clazz, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    }
    } catch (KeeperException e) {
    e.printStackTrace();
    } catch (InterruptedException e) {
    e.printStackTrace();
    } finally {
    close();
    }
    }

    private static AtomicInteger index = new AtomicInteger(0);

    /**
    * a simple load balance implement
    * @param path
    * @return
    * @throws KeeperException
    * @throws InterruptedException
    */

    public String getData(String path) throws KeeperException, InterruptedException {
    String host = null;
    String serviceName = null;
    try {
    connect();
    List<String> children = zkConn.getChildren(path, false);
    if (children == null || children.size() <= 0)
    return null;
    if (index.get() >= children.size()) {
    index.set(0);
    host = children.get(index.get());
    } else {
    host = children.get(index.getAndIncrement());
    }
    Stat stat = new Stat();
    byte[] data = zkConn.getData(path + "/" + host, null, stat);
    serviceName = new String(data);
    } finally {
    close();
    }
    return host + serviceName;
    }
    /**
    * Connect success callback
    */

    class ConnectWatcher implements Watcher {

    private final CountDownLatch semaphore;

    private ConnectWatcher(CountDownLatch semaphore) {
    this.semaphore = semaphore;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
    if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
    if (Event.EventType.None == watchedEvent.getType() && watchedEvent.getPath() == null) {
    System.out.println("ZK connect success!");
    semaphore.countDown();
    }
    }
    }
    }


    /**
    * Create a asynchronized node
    *
    * @param path
    * @param data
    * @param acl
    * @param createMode
    * @param cb
    * @param ctx
    * @throws KeeperException
    * @throws InterruptedException
    */

    public boolean create(String path, String data, List<ACL> acl, CreateMode createMode, AsyncCallback.StringCallback cb, Object ctx) throws KeeperException, InterruptedException {
    Stat rootStat = zkConn.exists(path, false);
    boolean result = false;
    if (rootStat == null) {
    zkConn.create(path, data.getBytes(), acl, createMode, cb, ctx);
    result = true;
    }
    return result;
    }

    /**
    * Create synchronized node
    *
    * @param path
    * @param data
    * @param acl
    * @param createMode
    * @throws KeeperException
    * @throws InterruptedException
    */

    public void create(String path, String data, List<ACL> acl, CreateMode createMode) throws KeeperException, InterruptedException {
    Stat rootStat = zkConn.exists(path, false);
    if (rootStat == null) {
    zkConn.create(path, data.getBytes(), acl, createMode);
    }
    }

    /**
    * Create dubbo node callback by WatcherManager
    */

    class CreateDubboCallback implements AsyncCallback.StringCallback {

    @Override
    public void processResult(int rc, String path, Object ctx, String name) {
    System.out.println("Create dubbo node callback by WatcherManager");
    if (path == null || "".equals(path)) {
    System.out.println("Create " + path + " failure!");
    return;
    } else {
    System.out.println("Create " + path + " success!");
    }
    try {
    // Create service node
    create(serviceNode, serviceNode, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new CreateServiceCallback(), "create service node");
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    /**
    * Create service node callback by WatcherManager
    */

    class CreateServiceCallback implements AsyncCallback.StringCallback {

    @Override
    public void processResult(int rc, String path, Object ctx, String name) {
    System.out.println("Create service node callback by WatcherManager");
    if (path == null || "".equals(path)) {
    System.out.println("Create " + path + " failure!");
    return;
    } else {
    System.out.println("Create " + path + " success!");
    }
    // Create service node
    try {
    create(businessNode, businessNode, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new CreateProviderCallback(), "create provider node");
    } catch (Exception e) {
    e.printStackTrace();
    ;
    }
    }
    }

    /**
    * Create provider node callback by WatcherManager
    */

    class CreateProviderCallback implements AsyncCallback.StringCallback {

    @Override
    public void processResult(int rc, String path, Object ctx, String name) {
    System.out.println("Create provide node callback by WatcherManager");
    if (path == null || "".equals(path)) {
    System.out.println("Create " + path + " failure!");
    return;
    } else {
    System.out.println("Create " + path + " success!");
    }
    // create host node
    try {
    create(hostNode, clazz, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    private void close(){
    Runtime.getRuntime().addShutdownHook(new Thread(){
    @Override
    public synchronized void start() {
    try {
    zkConn.close();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    }
    }
  • 服务提供者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package org.zk.naming;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;

import java.util.concurrent.CountDownLatch;

/**
* Created by zhengzhi.ren on 2015/7/24.
*/

public class Provider {

public static void main(String[] args) throws InterruptedException {
ZKClient client = new ZKClient("/dubbo", "/org.zk.naming.HelloWorldService", "/org.zk.naming.HelloWorldServiceImpl", "/providers", "/127.0.0.1:20881");
client.createNode();

client = new ZKClient("/dubbo", "/org.zk.naming.HelloWorldService", "/org.zk.naming.HelloWorldServiceImpl", "/providers", "/127.0.0.1:20882");
client.createNode();
CountDownLatch semaphore = new CountDownLatch(1);
semaphore.await();
}
}
  • 服务调用者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package org.zk.naming;

import org.apache.zookeeper.KeeperException;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
* Created by zhengzhi.ren on 2015/7/24.
*/

public class Consumer {

public static void main(String[] args) throws InterruptedException, KeeperException {
ZKClient client = new ZKClient("/dubbo", "/org.zk.naming.HelloWorldService", "", "/consumers", "/127.0.0.1:2181");
client.createNode();

String serviceName = client.getData("/dubbo/org.zk.naming.HelloWorldService/providers");
System.out.println("The provider info: " + serviceName);

serviceName = client.getData("/dubbo/org.zk.naming.HelloWorldService/providers");
System.out.println("The provider info: " + serviceName);

serviceName = client.getData("/dubbo/org.zk.naming.HelloWorldService/providers");
System.out.println("The provider info: " + serviceName);
CountDownLatch semaphore = new CountDownLatch(1);
semaphore.await();
}
}
原创技术文章,转载请注明:转自http://newliferen.github.io/