1. 程式人生 > >SpringBoot2 整合 Zookeeper元件,管理架構中服務協調

SpringBoot2 整合 Zookeeper元件,管理架構中服務協調

本文原始碼:GitHub·點這裡 || GitEE·點這裡

一、Zookeeper基礎簡介

1、概念簡介

Zookeeper是一個Apache開源的分散式的應用,為系統架構提供協調服務。從設計模式角度來審視:該元件是一個基於觀察者模式設計的框架,負責儲存和管理資料,接受觀察者的註冊,一旦資料的狀態發生變化,Zookeeper就將負責通知已經在Zookeeper上註冊的觀察者做出相應的反應,從而實現叢集中類似Master/Slave管理模式。ZooKeeper的目標就是封裝好複雜易出錯的關鍵服務,將簡單易用的介面和效能高效、功能穩定的系統提供給使用者。

2、基本理論

  • 資料結構

ZooKeeper記錄資料的結構與Linux檔案系統相似,整體可以看作一棵樹,每個節點稱ZNode。每個Znode預設能夠儲存1MB的資料,每個ZNode都可以通過其路徑唯一標識。

  • 節點型別

短暫(ephemeral):客戶端和伺服器端斷開連線後,建立的節點自動刪除。
持久(persistent):客戶端和伺服器端斷開連線後,建立的節點持久化儲存。

  • 叢集服務

在Zookeeper叢集服務是由一個領導者(leader),多個跟隨者(follower)組成的叢集。領導者負責進行投票的發起和決議,更新叢集服務狀態。跟隨者用於接收客戶請求並向客戶端返回結果,在選舉Leader過程中參與投票。叢集中只要有半數以上節點存活,Zookeeper叢集就能正常服務。

  • 資料一致性

每個server儲存一份相同的資料拷貝,客戶端無論請求到被叢集中哪個server處理,得到的資料都是一致的。

3、應用場景

  • 經典應用:Dubbo框架的服務註冊和發現;
  • 分散式訊息同步和協調機制;
  • 伺服器節點動態上下線;
  • 統一配置管理、負載均衡、叢集管理;

二、安全管理操作

1、操作許可權

ZooKeeper的節點有5種操作許可權:CREATE(增)、READ(查)、WRITE(改)、DELETE(刪)、ADMIN(管理)等相關許可權,這5種許可權集合可以簡寫為crwda,每個單詞的首字元拼接而成。

2、認證方式:

  • world

預設方式,開放的許可權,意解為全世界都能隨意訪問。

  • auth

已經授權且認證通過的使用者才可以訪問。

  • digest

使用者名稱:密碼方式認證,實際業務開發中最常用的方式。

  • IP白名單

授權指定的Ip地址,和指定的許可權點,控制訪問。

3、Digest授權流程

  • 新增認證使用者

addauth digest 使用者名稱:密碼

  • 設定許可權

setAcl /path auth:使用者名稱:密碼:許可權

  • 檢視Acl設定

getAcl /path

  • 完整操作流程
-- 新增授權使用者
[zk: localhost:2181] addauth digest smile:123456
-- 建立節點
[zk: localhost:2181] create /cicada cicada
-- 節點授權
[zk: localhost:2181] setAcl /cicada auth:smile:123456:cdrwa
-- 檢視授權
[zk: localhost:2181] getAcl /cicada

三、整合 SpringBoot2 框架

1、核心依賴

Curator是Apache開源的一個Zookeeper客戶端連線和操作的元件,Curator框架在Zookeeper原生API介面上進行二次包裝。提供ZooKeeper各種應用場景:比如:分散式鎖服務、叢集領導選舉、共享計數器、快取機制、分散式佇列等API封裝。

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>2.12.0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>2.12.0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-client</artifactId>
    <version>2.12.0</version>
</dependency>

2、Zookeeper引數

zoo:
  keeper:
    #開啟標誌
    enabled: true
    #伺服器地址
    server: 127.0.0.1:2181
    #名稱空間,被稱為ZNode
    namespace: cicada
    #許可權控制,加密
    digest: smile:123456
    #會話超時時間
    sessionTimeoutMs: 3000
    #連線超時時間
    connectionTimeoutMs: 60000
     #最大重試次數
    maxRetries: 2
    #初始休眠時間
    baseSleepTimeMs: 1000

3、服務初始化配置

@Configuration
public class ZookeeperConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperConfig.class) ;
    @Resource
    private ZookeeperParam zookeeperParam ;
    private static CuratorFramework client = null ;
    /**
     * 初始化
     */
    @PostConstruct
    public void init (){
        //重試策略,初試時間1秒,重試10次
        RetryPolicy policy = new ExponentialBackoffRetry(
                zookeeperParam.getBaseSleepTimeMs(),
                zookeeperParam.getMaxRetries());
        //通過工廠建立Curator
        client = CuratorFrameworkFactory.builder()
                .connectString(zookeeperParam.getServer())
                .authorization("digest",zookeeperParam.getDigest().getBytes())
                .connectionTimeoutMs(zookeeperParam.getConnectionTimeoutMs())
                .sessionTimeoutMs(zookeeperParam.getSessionTimeoutMs())
                .retryPolicy(policy).build();
        //開啟連線
        client.start();
        LOGGER.info("zookeeper 初始化完成...");
    }
    public static CuratorFramework getClient (){
        return client ;
    }
    public static void closeClient (){
        if (client != null){
            client.close();
        }
    }
}

4、封裝系列介面

public interface ZookeeperService {
    /**
     * 判斷節點是否存在
     */
    boolean isExistNode (final String path) ;
    /**
     * 建立節點
     */
    void createNode (CreateMode mode,String path ) ;
    /**
     * 設定節點資料
     */
    void setNodeData (String path, String nodeData) ;
    /**
     * 建立節點
     */
    void createNodeAndData (CreateMode mode, String path , String nodeData) ;
    /**
     * 獲取節點資料
     */
    String getNodeData (String path) ;
    /**
     * 獲取節點下資料
     */
    List<String> getNodeChild (String path) ;
    /**
     * 是否遞迴刪除節點
     */
    void deleteNode (String path,Boolean recursive) ;
    /**
     * 獲取讀寫鎖
     */
    InterProcessReadWriteLock getReadWriteLock (String path) ;
}

5、介面實現

@Service
public class ZookeeperServiceImpl implements ZookeeperService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperServiceImpl.class);
    @Override
    public boolean isExistNode(String path) {
        CuratorFramework client = ZookeeperConfig.getClient();
        client.sync() ;
        try {
            Stat stat = client.checkExists().forPath(path);
            return client.checkExists().forPath(path) != null;
        } catch (Exception e) {
            LOGGER.error("isExistNode error...", e);
            e.printStackTrace();
        }
        return false;
    }
    @Override
    public void createNode(CreateMode mode, String path) {
        CuratorFramework client = ZookeeperConfig.getClient() ;
        try {
            // 遞迴建立所需父節點
            client.create().creatingParentsIfNeeded().withMode(mode).forPath(path);
        } catch (Exception e) {
            LOGGER.error("createNode error...", e);
            e.printStackTrace();
        }
    }
    @Override
    public void setNodeData(String path, String nodeData) {
        CuratorFramework client = ZookeeperConfig.getClient() ;
        try {
            // 設定節點資料
            client.setData().forPath(path, nodeData.getBytes("UTF-8"));
        } catch (Exception e) {
            LOGGER.error("setNodeData error...", e);
            e.printStackTrace();
        }
    }
    @Override
    public void createNodeAndData(CreateMode mode, String path, String nodeData) {
        CuratorFramework client = ZookeeperConfig.getClient() ;
        try {
            // 建立節點,關聯資料
            client.create().creatingParentsIfNeeded().withMode(mode)
                  .forPath(path,nodeData.getBytes("UTF-8"));
        } catch (Exception e) {
            LOGGER.error("createNode error...", e);
            e.printStackTrace();
        }
    }
    @Override
    public String getNodeData(String path) {
        CuratorFramework client = ZookeeperConfig.getClient() ;
        try {
            // 資料讀取和轉換
            byte[] dataByte = client.getData().forPath(path) ;
            String data = new String(dataByte,"UTF-8") ;
            if (StringUtils.isNotEmpty(data)){
                return data ;
            }
        }catch (Exception e) {
            LOGGER.error("getNodeData error...", e);
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public List<String> getNodeChild(String path) {
        CuratorFramework client = ZookeeperConfig.getClient() ;
        List<String> nodeChildDataList = new ArrayList<>();
        try {
            // 節點下資料集
            nodeChildDataList = client.getChildren().forPath(path);
        } catch (Exception e) {
            LOGGER.error("getNodeChild error...", e);
            e.printStackTrace();
        }
        return nodeChildDataList;
    }
    @Override
    public void deleteNode(String path, Boolean recursive) {
        CuratorFramework client = ZookeeperConfig.getClient() ;
        try {
            if(recursive) {
                // 遞迴刪除節點
                client.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
            } else {
                // 刪除單個節點
                client.delete().guaranteed().forPath(path);
            }
        } catch (Exception e) {
            LOGGER.error("deleteNode error...", e);
            e.printStackTrace();
        }
    }
    @Override
    public InterProcessReadWriteLock getReadWriteLock(String path) {
        CuratorFramework client = ZookeeperConfig.getClient() ;
        // 寫鎖互斥、讀寫互斥
        InterProcessReadWriteLock readWriteLock = new InterProcessReadWriteLock(client, path);
        return readWriteLock ;
    }
}

6、基於Swagger2介面

@Api("Zookeeper介面管理")
@RestController
public class ZookeeperApi {
    @Resource
    private ZookeeperService zookeeperService ;
    @ApiOperation(value="查詢節點資料")
    @GetMapping("/getNodeData")
    public String getNodeData (String path) {
        return zookeeperService.getNodeData(path) ;
    }
    @ApiOperation(value="判斷節點是否存在")
    @GetMapping("/isExistNode")
    public boolean isExistNode (final String path){
        return zookeeperService.isExistNode(path) ;
    }
    @ApiOperation(value="建立節點")
    @GetMapping("/createNode")
    public String createNode (CreateMode mode, String path ){
        zookeeperService.createNode(mode,path) ;
        return "success" ;
    }
    @ApiOperation(value="設定節點資料")
    @GetMapping("/setNodeData")
    public String setNodeData (String path, String nodeData) {
        zookeeperService.setNodeData(path,nodeData) ;
        return "success" ;
    }
    @ApiOperation(value="建立並設定節點資料")
    @GetMapping("/createNodeAndData")
    public String createNodeAndData (CreateMode mode, String path , String nodeData){
        zookeeperService.createNodeAndData(mode,path,nodeData) ;
        return "success" ;
    }
    @ApiOperation(value="遞迴獲取節點資料")
    @GetMapping("/getNodeChild")
    public List<String> getNodeChild (String path) {
        return zookeeperService.getNodeChild(path) ;
    }
    @ApiOperation(value="是否遞迴刪除節點")
    @GetMapping("/deleteNode")
    public String deleteNode (String path,Boolean recursive) {
        zookeeperService.deleteNode(path,recursive) ;
        return "success" ;
    }
}

四、原始碼地址

GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent

相關推薦

SpringBoot2 整合 Zookeeper元件管理架構服務協調

本文原始碼:GitHub·點這裡 || GitEE·點這裡 一、Zookeeper基礎簡介 1、概念簡介 Zookeeper是一個Apache開源的分散式的應用,為系統架構提供協調服務。從設計模式角度來審視:該元件是一個基於觀察者模式設計的框架,負責儲存和管理資料,接受觀察者的註冊,一旦資料的狀態發生變化,Z

SpringBoot2 整合JTA元件多資料來源事務管理

本文原始碼:[GitHub·點這裡](https://github.com/cicadasmile/middle-ware-parent) || [GitEE·點這裡](https://gitee.com/cicadasmile/middle-ware-parent) # 一、JTA元件簡介 ## 1、

SpringBoot2 整合Ehcache元件輕量級快取管理

本文原始碼:[GitHub·點這裡](https://github.com/cicadasmile/middle-ware-parent) || [GitEE·點這裡](https://gitee.com/cicadasmile/middle-ware-parent) # 一、Ehcache快取簡介 #

SpringBoot2 整合Nacos元件環境搭建和入門案例詳解

本文原始碼:GitHub·點這裡 || GitEE·點這裡 一、Nacos基礎簡介 1、概念簡介 Nacos 是構建以“服務”為中心的現代應用架構,如微服務正規化、雲原生正規化等服務基礎設施。聚焦於發現、配置和管理微服務。Nacos提供一組簡單易用的特性集,幫助開發者快速實現動態服務發現、服務配置、服務元資料

SpringBoot2 整合Kafka元件應用案例和流程詳解

本文原始碼:GitHub·點這裡 || GitEE·點這裡 一、搭建Kafka環境 1、下載解壓 -- 下載 wget http://mirror.bit.edu.cn/apache/kafka/2.2.0/kafka_2.11-2.2.0.tgz -- 解壓 tar -zxvf kafka_2.11-2.2

SpringBoot2 整合OAuth2元件模擬第三方授權訪問

本文原始碼:[GitHub·點這裡](https://github.com/cicadasmile/middle-ware-parent) || [GitEE·點這裡](https://gitee.com/cicadasmile/middle-ware-parent) # 一、模式描述 ![](http

SpringBoot2 整合ElasticJob框架定製化管理流程

本文原始碼:[GitHub·點這裡](https://github.com/cicadasmile/middle-ware-parent) || [GitEE·點這裡](https://gitee.com/cicadasmile/middle-ware-parent) # 一、ElasticJob簡介

springboot2整合zookeeper集成curator

初始化 臨時 except null 取消 turn ted with lose 步驟: 1- pom.xml <dependency> <groupId>org.apache.curator</groupId>

SpringCloud分布式事務實戰(七)在微服務1創建整合函數調用微服務2

request enable class alt cef 內容 llb 傳遞 turn (1) 添加jar pom.xml <dependency> <groupId>org.springframework.clou

Hadoop生態系統完整元件及其在架構的作用

(1)Hadoop生態系統(2)、HDFS(Hadoop分散式檔案系統)HDFS是Hadoop體系中資料儲存管理的基礎。它是一個高度容錯的系統,能檢測和應對硬體故障,用於在低成本的通用硬體上執行。HDF

在ui介面新增Qlabel控制元件在QLabel使用QMovie播放gif

#include "WaitDialog.h" #include<QPainter> #include<QMovie> WaitDialog::WaitDialog(QWidget *parent, QString fileName, int pic

SpringCloud微服務:Sentinel哨兵元件管理服務限流和降級

原始碼地址:[GitHub·點這裡](https://github.com/cicadasmile/spring-cloud-base)||[GitEE·點這裡](https://gitee.com/cicadasmile/spring-cloud-base) # 一、基本簡介 ## 1、概念描述 Se

SpringBoot2 整合FreeMarker模板完成頁面靜態化處理

本文原始碼:[GitHub·點這裡](https://github.com/cicadasmile/middle-ware-parent) || [GitEE·點這裡](https://gitee.com/cicadasmile/middle-ware-parent) # 一、頁面靜態化 ## 1、動靜

品優購專案筆記day01——(SOA架構Dubbox及小demoZookeeper專案打包管理中心linux環境部署與專案架構搭建)

此部落格是為了記錄業餘時間每一天課程的所學 1.什麼是SOA架構 SOA是Service-Oriented Architecture的首字母簡稱,它是一種支援面向服務的架構樣式。從服務、基於服務開發和服務的結果來看,面向服務是一種思考方式。其實SOA架構更多應用於網際網路專案開發。

架構元件深挖istio如何連線、管理和保護微服務2.0?_Kubernetes中文社群

近幾年我一直從事於微服務系統的設計以及實現方面的工作,屬於微服務架構一線實踐者。之前做過一些單體系統的微服務改造,在微服務拆分、治理等方面都有一定的經驗。 本人比較特殊一點的經歷是既做過 IT 領域的微服務,也做過 CT(通訊領域)的微服務,微服務架構在這兩個領域的具體形態和要求是不太一樣的,

SpringBoot2.0高階案例(12):整合 SpringSecurity 框架實現使用者許可權安全管理

一、Security簡介 1、基礎概念 Spring Security是一個能夠為基於Spring的企業應用系統提供宣告式的安全訪

架構設計 | 分散式系統排程Zookeeper叢集化管理

本文原始碼:[GitHub·點這裡](https://github.com/cicadasmile/data-manage-parent) || [GitEE·點這裡](https://gitee.com/cicadasmile/data-manage-parent) # 一、框架簡介 ## 1、基礎簡

SpringBoot2 整合MinIO中介軟體實現檔案便捷管理

本文原始碼:[GitHub·點這裡](https://github.com/cicadasmile/middle-ware-parent) || [GitEE·點這裡](https://gitee.com/cicadasmile/middle-ware-parent) # 一、MinIO簡介 ## 1、

從資源管理獲取被選擇的文件的路徑(及文件夾)的API

nis ont ftp bstr http api lib 管理 als 從下面的URL中,獲得了這個Library.Get paths of selected items in an explorer window /* http://www.autohotke

MySQL(三):MHA實現MySQL主從架構服務器的高可用zabbix完成manager重啟

code parallel 可以登錄 authorize sudo word systemctl 命令 nag MHA(Master High Availability)是目前在MySQL高可用方面相對成熟的一個解決方案,MHA在監控到master節點故障時,會提升其中擁有