Zookeeper Linux stand-alone installation and springboot integration are basically used to add, delete, modify and check

1. Linux stand-alone installation of Zookeeper

First, let’s download zookeeper’s official website and download my version 3.5.6 (taken by yourself). Students who just want to see springboot integration skip it and watch it directly.
Link: https://pan.baidu.com/s/1HnBsSz_AP6P_vEIqe5wlBQ
Extraction code: qzsv

  • Upload to the Linux server and use the command tar -zxvf package name to decompress
    insert image description here

  • Enter the folder First, we copy the configuration file and enter the conf directory cp zoo_sample.cfg zoo.cfg
    insert image description here

  • Edit the zoo.cfg configuration file vi zoo.cfg Open the port Set the two file storage paths of dataDir and dataLogDir and save and exit
    insert image description here

  • Enter bin/zkServer.sh start to start zookeeper
    insert image description here

  • After the startup is complete, enter jps to check whether the process exists
    insert image description here

  • Enter bin/zkCli.sh to enter zookeeper
    insert image description here

这里我们可以输入 一些简单操作命令 进行操作  详细内容可以网上搜索这里不一一介绍 (操作如下图所示)
ls /           //查看根目录所有节点
create /testNode 我是测试内容      //create创建节点 
get /testNode      //获取节点信息
set /testNode  我是更新后的测试数据

insert image description here

2. Springboot integrated operation node addition, deletion, modification and query

directly on the code

//pom依赖
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.5.5</version>
        </dependency>
		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>


//appication.properties 配置文件
# 项目配置端口
server.port=9809          
# zookeeper ip 端口
zookeeper.address=ip:2181
#连接超时
zookeeper.address.timeout=4000

configuration configuration class code can run directly, students who can’t run just introduce dependency problem, you can check import carefully

//configuration 配置类
import com.example.demoalgorithm.controller.ZookeeperTest;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.CountDownLatch;

@Configuration
public class ZookeeperConfig {
    
    
    @Value("${zookeeper.address}")
    private String connectString;

    @Value(("${zookeeper.address.timeout}"))
    private int timeout;

    @Bean(name = "zkClient")
    public ZooKeeper zkClient(){
    
    
        ZooKeeper zooKeeper=null;
        try {
    
    
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            zooKeeper = new ZooKeeper(connectString, timeout, new Watcher() {
    
    
                @Override
                public void process(WatchedEvent event) {
    
    
                    if(Event.KeeperState.SyncConnected==event.getState()){
    
         
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
            System.out.println(zooKeeper.getState()+"ZooKeeper状态");
            logger.info("ZooKeeper连接状态={}",zooKeeper.getState());
        }catch (Exception e){
    
    
            logger.error("初始化ZooKeeper异常={}",e);
        }
        return  zooKeeper;
    }

}

After adding the configuration proxy class, directly perform the zookeeper connection test

import com.example.demoalgorithm.config.ZkApi;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import static org.apache.zookeeper.ZooDefs.OpCode.exists;

@RestController
public class ZookeeperTest {
    
    
    private static final Logger logger = LoggerFactory.getLogger(ZookeeperTest.class);
    @Autowired
    private ZooKeeper zkClient;
    
	// 查询节点是否存在 参数:节点路径  例如 /testNode
    @GetMapping("selectNode")
    public void selectNode(String path){
    
    
        try {
    
    
            logger.info("[开始查询节点Stat]");
            Stat exists = zkClient.exists(path, true);
            logger.info("[查询成功]",exists.getVersion());
        } catch (KeeperException e) {
    
    
            e.printStackTrace();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }

    //查询节点数据 此方法返回节点内数据 参数:节点路径 例如 /testNode
    @GetMapping("queryData")
    public  String queryData(String nodePath) throws KeeperException, InterruptedException{
    
    
        Stat stat = zkClient.exists(nodePath, false);
        logger.info("准备查询节点Stat,path:{}",nodePath);
        //data 为节点内数据
        String data = new String(zkClient.getData(nodePath, false, stat));
        logger.info("结束查询节点Stat,data:{}", data);
        return data;
    }

    //此方法为创建节点 参数:节点路径  节点数据  例如:/testNode  测试数据
    @GetMapping("/createNode")
    public void create(String nodePath,String nodeData) throws KeeperException, InterruptedException{
    
    
        logger.info("开始创建节点:{},数据:{}",nodePath,nodeData);
        List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
        CreateMode createMode = CreateMode.PERSISTENT;
        // result 节点名
        String result = zkClient.create(nodePath, nodeData.getBytes(), acl, createMode);
        logger.info("创建节点返回结果:{}",result);
        logger.info("完成创建节点:{}, 数据:{}",nodePath,nodeData);
    }



 // 修改接口 
    @GetMapping("updateNode")
    public  Stat update(String nodePath,String nodeData) throws KeeperException, InterruptedException{
    
    
        Stat stat = zkClient.exists(nodePath, false);
        logger.info("准备修改节点,path:{},data:{},version:{}",nodePath,nodeData,stat.getVersion());
        Stat newStat = zkClient.setData(nodePath, nodeData.getBytes(), stat.getVersion());
        logger.info("修改节点完成,path:{},data:{},version:{}",nodePath,nodeData,stat.getVersion()); 
        return stat;
    }

//删除接口 
    @GetMapping("deleteNode")
    public String delete(String nodePath) throws InterruptedException, KeeperException{
    
    
        //删除节点前先查询该节点信息
        Stat stat = zkClient.exists(nodePath, false);
        logger.info("准备删除节点,path:{},原version:{}",nodePath, stat.getVersion());
        zkClient.delete(nodePath, stat.getVersion());
        logger.info("完成删除节点,path:{0}",nodePath);
		return "success";
    }

}

Guess you like

Origin blog.csdn.net/pgcdnameming/article/details/121564742