4. springboot集成zk进行curd操作

  1. 首先需要引入zk相关的依赖
<!--引入zk客户端依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.0.0</version>
        </dependency>
        <!--zk依赖结束-->
  1. 添加zk客户端配置类
@Configuration
public class ZookeeperConfig {

    private String host = "127.0.0.1:2181";

    @Bean
    public CuratorFramework curatorFramework() {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(host)
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        curatorFramework.start();
        return curatorFramework;
    }
}

此处的ip,port可以方式在配置文件中进行读取.

  1. 在使用的时候,将服务引入,如图:
    在这里插入图片描述
  2. 新建controller,操作zk
package com.yutu.fileupload.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@RequestMapping("/zk")
@RestController
public class ZkController {

    @Resource
    private CuratorFramework curatorFramework;

    /**
     * 检查节点是否存在
     */
    @GetMapping("/isExistNode")
    public String isExistNode(@RequestParam String nodeName) {
        try {
            Stat stat = curatorFramework.checkExists().forPath(nodeName);
            return "stat: " + stat;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "nothing";
    }

    /**
     * 创建节点
     */
    @GetMapping("/createNode")
    public String createNode(@RequestParam String nodeName) {
        try {
            curatorFramework.create()
                    // 如果有子节点会递归创建
                    .creatingParentsIfNeeded()
                    // 设置为持久节点
                    .withMode(CreateMode.PERSISTENT).forPath(nodeName);
            return "success create node";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "failed";
    }

    /**
     * 更新节点数据
     */
    @GetMapping("/setNodeValue")
    public String setNodeValue(@RequestParam String nodeName, @RequestParam String nodeValue) {
        try {
            curatorFramework.setData().forPath(nodeName, nodeValue.getBytes(StandardCharsets.UTF_8));
            return "update node values success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "update failed";
    }



}

注意,给节点设置value成功,如图:
在这里插入图片描述
打开客户端工具,查看是否成功:
在这里插入图片描述
5. 创建节点并设置数据:

@GetMapping("/createNodeAndValue")
    public String createNodeAndValue(@RequestParam String nodeName, @RequestParam String nodeValue) {
        try {
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                    .forPath(nodeName, nodeValue.getBytes(StandardCharsets.UTF_8));
            return "创建节点并设置数据: success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "创建节点并设置数据: failed";
    }

在这里插入图片描述
在这里插入图片描述
6. 查询节点数据:

/**
     * 查询节点数据
     */
    @GetMapping("/queryNodeValue")
    public String queryNodeValue(@RequestParam String nodeName) {
        try {
            String s = new String(curatorFramework.getData().storingStatIn(new Stat()).forPath(nodeName));
            return "查询节点数据valus: " + s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "查询节点数据: failed ";
    }

在这里插入图片描述
7. 查询节点下的所有子节点:

@GetMapping("/queryNodeChild")
    public String queryNodeChild(@RequestParam String nodeName) {
        try {
            List<String> strings = curatorFramework.getChildren().forPath(nodeName);
            return "查询节点下所有子节点: " + strings;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "查询节点下所有子节点: failed" ;
    }

在这里插入图片描述
附完整的controller:

package com.yutu.fileupload.controller;

import com.alibaba.fastjson.JSONObject;
import com.yutu.fileupload.pojo.AjaxResult;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RequestMapping("/zk")
@RestController
public class ZkController {

    @Resource
    private CuratorFramework curatorFramework;

    /**
     * 检查节点是否存在
     */
    @GetMapping("/isExistNode")
    public String isExistNode(@RequestParam String nodeName) {
        try {
            Stat stat = curatorFramework.checkExists().forPath(nodeName);
            return "stat: " + stat;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "nothing";
    }

    /**
     * 创建节点
     */
    @GetMapping("/createNode")
    public String createNode(@RequestParam String nodeName) {
        try {
            curatorFramework.create()
                    // 如果有子节点会递归创建
                    .creatingParentsIfNeeded()
                    // 设置为持久节点
                    .withMode(CreateMode.PERSISTENT).forPath(nodeName);
            return "success create node";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "failed";
    }

    /**
     * 更新节点数据
     */
    @GetMapping("/setNodeValue")
    public String setNodeValue(@RequestParam String nodeName, @RequestParam String nodeValue) {
        try {
            curatorFramework.setData().forPath(nodeName, nodeValue.getBytes(StandardCharsets.UTF_8));
            return "update node values success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "update failed";
    }

    /**
     * 2. 创建节点并设置数据
     */
    @GetMapping("/createNodeAndValue")
    public String createNodeAndValue(@RequestParam String nodeName, @RequestParam String nodeValue) {
        try {
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                    .forPath(nodeName, nodeValue.getBytes(StandardCharsets.UTF_8));
            return "创建节点并设置数据: success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "创建节点并设置数据: failed";
    }

    /**
     * 查询节点数据
     */
    @GetMapping("/queryNodeValue")
    public String queryNodeValue(@RequestParam String nodeName) {
        try {
            String s = new String(curatorFramework.getData().storingStatIn(new Stat()).forPath(nodeName));
            return "查询节点数据valus: " + s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "查询节点数据: failed ";
    }

    /**
     * 查询节点下的所有子节点
     */
    @GetMapping("/queryNodeChild")
    public String queryNodeChild(@RequestParam String nodeName) {
        try {
            List<String> strings = curatorFramework.getChildren().forPath(nodeName);
            return "查询节点下所有子节点: " + strings;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "查询节点下所有子节点: failed" ;
    }

    /**
     * 递归删除
     */
    @GetMapping("/deleteNode")
    public AjaxResult deleteNode(@RequestParam String nodeName) {
        try {
            // guaranteed 用来保证如果删除失败,则会话有效期内一直尝试删除
            // deletingChildrenIfNeeded 表示如果有子节点,则递归删除
            return AjaxResult.ok(curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath(nodeName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error(null);
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值