文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

SpringBoot整合Zookeeper详细教程

2022-12-23 15:00

关注

一、引言

使用原生的zookeeper时候会遇到watcher一次注册生效一次等情况,因此使用curator

curator是Netflix公司开源的一个 zookeeper客户端原生API接口上进行了包装,解决了很多问题并提供Zookeeper分布式锁服务、集群领导选举、共享计数器、缓存机制、分布式队列等的应用的抽象封装

二、引入依赖

<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.6.2</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.10</version>
</dependency>

三、编写客户端

要改Windows的host文件。host文件位置是C:\Windows\System32\drivers\etc

3.1、ZookeeperConfig

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ZookeeperConfig {
    //集群地址,分割不能有空格 在程序里写connectString不可使用ip,必须使用主机名
    private String connectString = "master:2181,slave1:2181,slave2:2181";
    //连接超时时间
    private int sessionTimeout = 5000;
    //会话存活时间,根据业务灵活指定
    private Integer sessionTimeOut=5000;
    //重试机制时间参数
    private Integer sleepMsBetweenRetry=1000;
    //重试机制重试次数
    private Integer maxRetries=3;
    //命名空间(父节点名称)
    private String namespace="";
    
    @Bean("curatorClient")
    public CuratorFramework curatorClient() throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(connectString)
                .connectionTimeoutMs(sessionTimeout)
                .sessionTimeoutMs(sessionTimeOut)
                //session重连策略
                .retryPolicy(new ExponentialBackoffRetry(sleepMsBetweenRetry,maxRetries))
                //设置命名空间 在操作节点的时候,会以这个为父节点
                .namespace(namespace)
                .build();
        client.start();
        //注册监听器
        ZookeeperWatches watches = new ZookeeperWatches(client);
        watches.znodeWatcher();
        watches.znodeChildrenWatcher();
        return client;
    }
}

3.2、ZookeeperWatches

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.zookeeper.data.Stat;
public class ZookeeperWatches {
    private CuratorFramework client;
    public ZookeeperWatches(CuratorFramework client) {
        this.client = client;
    }
    public void znodeWatcher() throws Exception {
        NodeCache nodeCache = new NodeCache(client, "/");
        nodeCache.start();
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("=======节点改变===========");
                String path = nodeCache.getPath();
                String currentDataPath = nodeCache.getCurrentData().getPath();
                String currentData = new String(nodeCache.getCurrentData().getData());
                Stat stat = nodeCache.getCurrentData().getStat();
                System.out.println("path:"+path);
                System.out.println("currentDataPath:"+currentDataPath);
                System.out.println("currentData:"+currentData);
            }
        });
        System.out.println("节点监听注册完成");
    }
    public void znodeChildrenWatcher() throws Exception {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/",true);
        pathChildrenCache.start();
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                System.out.println("=======节点子节点改变===========");
                PathChildrenCacheEvent.Type type = event.getType();
                String childrenData = new String(event.getData().getData());
                String childrenPath = event.getData().getPath();
                Stat childrenStat = event.getData().getStat();
                System.out.println("子节点监听类型:"+type);
                System.out.println("子节点路径:"+childrenPath);
                System.out.println("子节点数据:"+childrenData);
                System.out.println("子节点元数据:"+childrenStat);
            }
        });
        System.out.println("子节点监听注册完成");
    }
}

3.3、ZookeeperController

@RestController
@RequestMapping(value = "/zookeeper")
public class ZookeeperController {
    @Resource(name = "curatorClient")
    private CuratorFramework client;
    @RequestMapping("/createZnode")
    public String createZnode(){
        String path = "/nacl";
        String data = "shuaige";
        List<ACL> aclList = new ArrayList<>();
        Id id = new Id("world", "anyone");
        aclList.add(new ACL(ZooDefs.Perms.ALL, id));
        try {
            client.create()
                    .creatingParentsIfNeeded()  //没有父节点时 创建父节点
                    .withMode(CreateMode.PERSISTENT)  //节点类型
                    .withACL(aclList)   //配置权限
                    .forPath(path, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return "节点创建失败"+e.getMessage();
        }
        return "节点创建成功";
    }
    @RequestMapping("/selectZnode")
    public String  selectZnode(){
        HashMap<String,String> hashMap=new HashMap();
        String path="/nacl";
        Stat stat;
        try {
            stat = client.checkExists().forPath(path);
            if (stat == null) {
                hashMap.put("Error","不存在该节点");
            }
            String dataString = new String(client.getData().forPath(path));
            hashMap.put(path, dataString);
            hashMap.put("stat", stat.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(hashMap);
    }
    @RequestMapping("/selectChildrenZnode")
    public String selectChildrenZnode(){
        Map<String, String> hashMap = new HashMap<>();
        String path="/";
        try {
            List<String> list = client.getChildren().forPath(path);
            for (String s : list) {
                String dataString = new String(client.getData().forPath(path+s));
                hashMap.put(path+s, dataString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(hashMap);
    }
    @RequestMapping("/setData")
    public String setData() {
        String path="/nacl";
        String data="big";
        Integer version=0;
        HashMap<String,String> hashMap=new HashMap<>();
        try {
            Stat stat = client.setData().withVersion(version).forPath(path, data.getBytes());
            hashMap.put("success", "修改成功");
            hashMap.put("version", String.valueOf(stat.getVersion()));
        } catch (Exception e) {
            e.printStackTrace();
            hashMap.put("error", "修改失败:"+e.getMessage());
        }
        return JSON.toJSONString(hashMap);
    }
    @RequestMapping("/delete")
    public String delete() {
        HashMap<String,String> hashMap=new HashMap<>();
        String path="/nacl";
        String data="big";
        Integer version=1;
        try {
            client.delete().withVersion(version).forPath(path);
            hashMap.put("success", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            hashMap.put("error", "删除失败:"+e.getMessage());
        }
        return JSON.toJSONString(hashMap);
    }
    @RequestMapping("/createAsyncZnode")
    public String createAsyncZnode(){
        String path = "/nacl";
        String data = "shuaige";
        try {
            client.create()
                    .creatingParentsIfNeeded()
                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                    //异步回调   增删改都有异步方法
                    .inBackground(new BackgroundCallback() {
                        @Override
                        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                            System.out.println("异步回调--获取权限:"+client.getACL().forPath(path));
                            System.out.println("异步回调--获取数据:"+new String(client.getData().forPath(path)));
                            System.out.println("异步回调--获取事件名称:"+event.getName());
                            System.out.println("异步回调--获取事件类型:"+event.getType());
                        }
                    })
                    .forPath(path, data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return "节点创建失败"+e.getMessage();
        }
        return "节点创建成功";
    }
}

到此这篇关于SpringBoot整合Zookeeper详细教程的文章就介绍到这了,更多相关SpringBoot整合Zookeeper内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯