1. 程式人生 > 其它 >【Zookeeper】知識點

【Zookeeper】知識點

1 zookeeper是什麼?

Zookeeper是一個分散式、開源的分散式應用程式的協調服務,是一個樹形的目錄服務

主要功能:

  • 配置管理
  • 分散式鎖
  • 叢集管理

2 zookeeper入門

2.1命令

啟動服務端:./zkServer.sh start

關閉伺服器:./zkServer.sh stop

啟動客戶端:./zkCli.sh -server localhost:2181

退出客戶端:quit

檢視節點狀態:./zkServer.sh status

檢視命令幫助:help

顯示指定目錄下節點:ls 目錄

顯示指定目錄詳細資訊:ls -s 目錄

建立節點:create [-es] /節點path value

獲取節點值:get /節點path

設定節點值:set /節點path value

刪除單個節點:delete /節點path

刪除帶有子節點的節點:deleteall /節點path

2.1資料模型

 

 

  • Zookeeper是一個樹形目錄服務,其資料模型擁有一個層次化結構
  • 這裡面的每一個節點被稱為:ZNode,每個節點上都會儲存自己的資料和節點資訊
  • 節點可以擁有子節點,同時也允許少量(1MB)資料儲存在該節點下
  • 節點型別:
    • PERSISTENT:持久化目錄節點
    • PERSISTENT_SEQUENTIAL:持久化順序編號目錄節點 -s
    • EPHEMERAL:臨時目錄節點。當前會話未結束資料會一直存在 -e
    • EPHEMERAL_SEQUENTIAL:臨時順序編號目錄節點 -es

 

2.3Curator

Curator是Apache Zookeeper的Java客戶端庫
/**
 * @author olic
 * @date 2022/6/2814:25
 * @描述 Curator
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = JedisTests.class)
public class CuratorTests {
  
    private CuratorFramework client;
  
    /**
     * 建立連線
     */
    @Before
    @Test
    public void coon(){
        // connectString:多個地址用,隔開; connectionTimeoutMs:連線超時時間; retryPolicy:重試策略
        // minSessionTimeout, maxSessionTimeout:一般,客戶端連線zookeeper的時候,都會設定一個session timeout,如果超過這個時間client沒有zookeeper server有聯絡,則這個session被設定為過期(如果這個session上有臨時節點,則會被全部刪除),但是這個時間不是客戶端可以無限設定的,伺服器可以設定這兩個引數來限制客戶端設定的範圍
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
        client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .retryPolicy(retryPolicy)
                .namespace("phenom") //此時phenom就是'/'目錄
                .build();
        //開啟連線
        client.start();
    }
/**
     * 釋放資源
     */
    @After
    @Test
    public void close(){
       if(client != null){
           client.close();
       }
    }
/**
     * 建立節點
     */
    @Test
    public void create() throws Exception {
        // 建立節點不指定資料時,預設將當前客戶端的ip作為資料儲存
        String path = client.create()
          .creatingParentsIfNeeded()
          .withMode(CreateMode.PERSISTENT)
          .forPath("/app1/p1", "234".getBytes());
        System.out.println(path);
    }
/**
     * 查詢節點
     */
    @Test
    public void select() throws Exception {
        // 節點值
        byte[] bytes = client.getData().forPath("/app1");
        // 子節點
        List<String> sons = client.getChildren().forPath("/");
        // 節點狀態
        Stat stat = new Stat();
        client.getData().storingStatIn(stat);
        System.out.println("子節點列表:"+ sons);
        System.out.println("節點值為:"+ Arrays.toString(bytes));
        System.