天天看點

SpringCloud學習筆記八:Spring Cloud Zookeeper 實戰

Spring Cloud Zookeeper 的作用

zookeeper是對分布式服務提供協調服務的apache開源項目。具體原理在上一講中《SpringCloud學習筆記七:Spring Cloud Zookeeper 服務管理》都具體描述過,這一講我們話不多說,直接上代碼。

本次實戰基于springcloud zookeeper進行開發,具體pom檔案添加如下内容

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zookeeper-config</artifactId>
</dependency>
           

以及springcloud的版本管理

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Camden.SR2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
           

建立測試類,具體邏輯在測試類中展現

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class ZookeeperApplicationTests {

    String connectString = "127.0.0.1:2181";
    int sessionTimeout = 2000;
    private ZooKeeper zooCli;

    /**
     * 建立zookeeper服務
     *
     * @throws IOException
     */
    @Before
    public void init() throws IOException {
        zooCli = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                List<String> children = null;
                try {
                    children = zooCli.getChildren("/", true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (String child : children) {
                    System.out.println(child);
                }
                System.out.println("-----------------");
            }
        });
    }

    /**
     * 建立節點
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void createNode() throws KeeperException, InterruptedException {
        String path = zooCli.create("/bbb", "bruce is handsome".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(path);
    }

    /**
     * 監聽節點狀态,實際監聽邏輯已經遷移到建立zookeeper服務方法中
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void getDataAndWatch() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 判斷zookeeper節點是否存在
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat stat = zooCli.exists("/bruce", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }
}
           

在測試前,我們需要啟動zookeeper的服務端,不然代碼中監聽不到zookeeper服務,代碼會報錯。

繼續閱讀