zookeeper学习三

1.zookeeper的ACL(访问控制列表)

znode被创建时带有一个ACL列表(默认为word,表示anyone)

ACL包括:

scheme(验证方式):zookeeper提供了以下几种验证方式:

            digest:客户端用户名和密码。

            auth:不适用任何id。

            ip:IP地址验证。

            word:固定为anyone。

            super:在这种scheme情况下,对应的id拥有超级权限,可以做任何事情。

id(验证信息)

perms(权限):节点的权限主要有:

create  对子节点的create操作

read     对本节点GetChildren和GetData操作

write     对本节点SetData操作

delete  对子节点Delete操作

admin  对本节点setAcl操作

2.用shell操作ACL

1)首先连接到zookeeper

--1.查看ACL

--2.给节点加上ip的ACL

再次访问时,这样访问才行

--3.给节点加上digest的ACL

使用以下生成密码

test:test->test:V28q/NynI4JI3Rk54h0r8O5kMug=

访问时就是这样

--4.scheme中还有一个super

需要更改zkServer.sh

加入参数-Dzookeeper.DigestAuthenticationProvider.superDigest=super:gG7s8t3oDEtIqF6DM9LlI/R+9Ss=

3.java的操作(ZooKeeper)

public class ZKAclDemo {
  private static ZooKeeper zooKeeper;
  public static void main(String[] args) throws Exception {
    connetionZK("");
    // getZnodeData(zooKeeper, "/test2");//注意:如果/test2目录下没有值,会报空指针
    // getZnodeAcl(zooKeeper, "/testAcl", "testAcl".getBytes());
    // setZnodeAcl(zooKeeper, "/testAcl2", "testAcl2".getBytes());
    close();
  }

  /**
  * 获取数据
  * @param zooKeeper
  * @param path
  */
  public static void getZnodeData(ZooKeeper zooKeeper, String path) {
    try {
      zooKeeper.addAuthInfo("digest", "test:test".getBytes());
      byte[] bs = zooKeeper.getData(path, false, new Stat());
      System.out.println(new String(bs));
    } catch (KeeperException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  /**
  * 获取ACL
  * @param zooKeeper
  * @param path
  * @param bytes
  */
  public static void getZnodeAcl(ZooKeeper zooKeeper, String path, byte[] bytes) {
    try {
      zooKeeper.create(path, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
      System.out.println("创建节点:"+path);
      List<ACL> listAcl = zooKeeper.getACL(path, new Stat());
      for (ACL acl : listAcl) {
        System.out.println("权限scheme id:" + acl.getId());
        System.out.println("权限位:" + acl.getPerms());
      }
    } catch (KeeperException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  /**
  * 设置ACL
  * @param zooKeeper
  * @param path
  * @param bytes
  */
  public static void setZnodeAcl(ZooKeeper zooKeeper, String path, byte[] bytes) {
    try {
      List<ACL> listAcl = new ArrayList<ACL>();
      Id id = new Id("digest", getDigestUserPwd("testacl:testacl"));
      listAcl.add(new ACL(ZooDefs.Perms.ALL, id));
      // listAcl.add(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, id));//多个权限之间用 | 分隔
      String string = zooKeeper.create(path, bytes, listAcl, CreateMode.PERSISTENT);
      System.out.println("节点:"+string);

      zooKeeper.addAuthInfo("digest", "testacl:testacl".getBytes());
      // 获取该节点的acl权限信息
      List<ACL> aclList = zooKeeper.getACL(path, new Stat());
      for (ACL acl : aclList) {
        System.out.println("--------------------------");
        System.out.println("权限scheme id:" + acl.getId());
        System.out.println("权限位:" + acl.getPerms());
      }
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (KeeperException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  /**
  * 使用ip同理
  */

  /**
  * 获取生成的ID
  * @param id
  * @return
  * @throws NoSuchAlgorithmException
  */
  public static String getDigestUserPwd(String id) throws NoSuchAlgorithmException {
    return DigestAuthenticationProvider.generateDigest(id);
  }

  /**
  * 连接zk
  * @param zk
  * @throws IOException
  * @throws KeeperException
  * @throws InterruptedException
  */
  public static void connetionZK(String zk) throws IOException, KeeperException, InterruptedException {
    //zookeeper的ip:端口
    String path = "192.168.10.150:2181";
    zooKeeper = new ZooKeeper(path, 20*1000,null);
  }

  /**
  * 关闭zk
  */
  public static void close() {
    try {
      if (zooKeeper != null) {
        zooKeeper.close();
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

4.java的操作(curator)

public class ZKAclDemo2 {
  public static void main(String[] args) throws Exception {
    // curatorAcl_1();
    // curatorAcl_2();
    // curatorAcl_3();
    // curatorAcl_4();
  }

  /**
  * 使用curator连接zk创建节点
  * @throws Exception
  */
  public static void curatorAcl_1() throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, Integer.MAX_VALUE);
    CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.10.150:2181", retryPolicy);
    client.start();
    //判断是否连接上
    if (!client.blockUntilConnected(20, TimeUnit.SECONDS)) {
      client.close();
    }
    @SuppressWarnings("deprecation")
    boolean isZkCuratorStarted = client.isStarted();
    System.out.println("状态连接中吗:"+isZkCuratorStarted);
    /***ACL***/
    List<ACL> listAcl = new ArrayList<ACL>();
    Id id = new Id("digest", getDigestUserPwd("test:test"));
    listAcl.add(new ACL(ZooDefs.Perms.ALL, id));
    CreateBuilder createBuilder = client.create();
    ProtectACLCreateModeStatPathAndBytesable<String> pathAndBytesable =     createBuilder.creatingParentsIfNeeded();
    pathAndBytesable.withMode(CreateMode.PERSISTENT).withACL(listAcl).forPath("/curatoracl", "curatoracl".getBytes());
    if (client!=null) {
      client.close();
    }
    System.out.println("over...");
  }

  /**
  * 使用curator连接zk获取节点数据
  * @throws Exception
  */
  public static void curatorAcl_2() throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, Integer.MAX_VALUE);
    CuratorFramework client = CuratorFrameworkFactory.builder().authorization("digest", "test:test".getBytes())
      .connectString("192.168.10.150:2181")
      .sessionTimeoutMs(20000).retryPolicy(retryPolicy)
      //.namespace("workspace")//这句的意思会在连接的path前加上/workspace
      .build();
    client.start();
    //判断是否连接上
    if (client.blockUntilConnected(20, TimeUnit.SECONDS)) {
      @SuppressWarnings("deprecation")
      boolean isZkCuratorStarted = client.isStarted();
      System.out.println("状态连接中吗:"+isZkCuratorStarted);
      byte[] bytes = client.getData().forPath("/curatoracl");
      System.out.println(new String(bytes));
    }
    if (client!=null) {
      client.close();
    }
    System.out.println("over...");
  }

  /**
  * 使用curator连接zk修改ACL
  * @throws Exception
  */
  public static void curatorAcl_3() throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, Integer.MAX_VALUE);
    CuratorFramework client = CuratorFrameworkFactory.builder().authorization("digest", "test:test".getBytes())
      .connectString("192.168.10.150:2181")
      .sessionTimeoutMs(20000).retryPolicy(retryPolicy)
      .build();
    client.start();
    //判断是否连接上
    if (client.blockUntilConnected(20, TimeUnit.SECONDS)) {
      @SuppressWarnings("deprecation")
      boolean isZkCuratorStarted = client.isStarted();
      System.out.println("状态连接中吗:"+isZkCuratorStarted);
      List<ACL> aclList = new ArrayList<ACL>();
      Id id = new Id("digest", getDigestUserPwd("test2:test2"));
      aclList.add(new ACL(ZooDefs.Perms.ALL, id));
      client.setACL().withACL(aclList).forPath("/curatoracl");
    }
    if (client!=null) {
      client.close();
    }
    System.out.println("over...");
  }

  /**
  * 使用curator连接zk查看ACL
  * @throws Exception
  */
  public static void curatorAcl_4() throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, Integer.MAX_VALUE);
    CuratorFramework client = CuratorFrameworkFactory.builder().authorization("digest", "test2:test2".getBytes())
      .connectString("192.168.10.150:2181")
      .sessionTimeoutMs(20000).retryPolicy(retryPolicy)
      .build();
    client.start();
    //判断是否连接上
    if (client.blockUntilConnected(20, TimeUnit.SECONDS)) {
      @SuppressWarnings("deprecation")
      boolean isZkCuratorStarted = client.isStarted();
      System.out.println("状态连接中吗:"+isZkCuratorStarted);
      List<ACL> listAcl = client.getACL().forPath("/curatoracl");
      for (ACL acl : listAcl) {
        System.out.println("权限scheme id:" + acl.getId());
        System.out.println("权限位:" + acl.getPerms());
      }
    }
    if (client!=null) {
      client.close();
    }
    System.out.println("over...");
  }

  /**
  * 获取生成的ID
  * @param id
  * @return
  * @throws NoSuchAlgorithmException
  */
  public static String getDigestUserPwd(String id) throws NoSuchAlgorithmException {
    return DigestAuthenticationProvider.generateDigest(id);
  }
}

原文地址:https://www.cnblogs.com/ku-ku-ku/p/10986251.html

时间: 2024-10-07 08:32:36

zookeeper学习三的相关文章

[转帖]Zookeeper学习系列【一】 教会你Zookeeper的一些基础概念

Zookeeper学习系列[一] 教会你Zookeeper的一些基础概念 https://segmentfault.com/a/1190000018927058 前言 最近加入了部门的技术兴趣小组,被分配了Zookeeper的研究任务.在研究过程当中,发现Zookeeper由于其开源的特性和其卓越的性能特点,在业界使用广泛,有很多的应用场景,而这些不同的应用场景实际上底层的原理都是差不多的,只要你真正理解了Zookeeper的一些基础概念和机制,就能够触类旁通. 于是乎,在第一次和项目小组内成员

算法学习三阶段

?? 第一阶段:练经典经常使用算法,以下的每一个算法给我打上十到二十遍,同一时候自己精简代码, 由于太经常使用,所以要练到写时不用想,10-15分钟内打完,甚至关掉显示器都能够把程序打 出来. 1.最短路(Floyd.Dijstra,BellmanFord) 2.最小生成树(先写个prim,kruscal 要用并查集,不好写) 3.大数(高精度)加减乘除 4.二分查找. (代码可在五行以内) 5.叉乘.判线段相交.然后写个凸包. 6.BFS.DFS,同一时候熟练hash 表(要熟,要灵活,代码要

Jetty学习三:配置概览-需要配置什么

上一节讲述了怎么配置Jetty,这节将告诉你使用Jetty你需要配置些什么. 配置Server Server实例是Jetty服务端的中心协调对象,它为所有其他Jetty服务端组件提供服务和生命周期管理.在标准Jetty发布中,核心的服务端配置是在etc/jetty.xml文件中,你也能在其中包含其他服务端配置,可以包括: 1)ThreadPool Server实例提供了一个线程池,你可以在etc/jetty.xml中配置最大线程数和最小线程数. 2)Handlers Jetty服务端只能有一个H

ZigBee学习三 UART通信

ZigBee学习三 UART通信 本实验只对coordinator.c文件进行改动就可以实现串口的收发. 修改coordinator.c文件 byte GenericApp_TransID; // This is the unique message ID (counter) afAddrType_t GenericApp_DstAddr; unsigned char uartbuf[128];/**************************************************

Spark学习三:Spark Schedule以及idea的安装和导入源码

Spark学习三:Spark Schedule以及idea的安装和导入源码 标签(空格分隔): Spark Spark学习三Spark Schedule以及idea的安装和导入源码 一RDD操作过程中的数据位置 二Spark Schedule 三Idea导入spark源码 一,RDD操作过程中的数据位置 [hadoop001@xingyunfei001 spark-1.3.0-bin-2.5.0]$ bin/spark-shell --master local[2] val rdd = sc.t

mongodb学习(三)

菜鸟啊...先吐槽一下自己 一 准备工作: 1.安装服务端: 去官网下载 http://www.mongodb.org/downloads 其实也自带了客户端 shell 2.安装客户端: mongoVUE http://blog.mongovue.com/ 并不是完全免费 破解方法: http://yhv5.com/mongovue_480.html 将服务端下载下来后直接安装 我下载在D盘也安装在D盘的... 启动mongodb的服务端不需要各种命令....直接鼠标左键双击bin中的mong

c++ boost库学习三:实用工具

noncopyable 大家都知道定义一个空类的时候,它实际包含了构造函数,拷贝构造函数,赋值操作符和析构函数等. 这样就很容易产生一个问题,就是当用户调用A a(“^_^") 或者A c="^_^" 时会发生一些意想不到的行为,所以很多时候我们需要禁用这样的用法. 一种方法就是把拷贝构造函数和赋值操作符显式的定义为private,但是这样需要很多代码. 于是boost库为大家提供了一个简单的方法:只需要将类继承于noncopyable就可以了. #include "

scala学习三---文件里读取文本行

学习了scala的基本知识后,发现了scala是集函数式和指令式结合为一体的一种语言,代码更加简洁,但是对于用习惯了java的人来说,还真的不是一件易事~~ 今天学习scala脚本读取文本文件 列子如下: import scala.io.Source if(args.length>0){ for(line <- Source.fromFile(args(0)).getLines) print(line.length+" "+line) }else{ Console.err.

Oracle学习(三):单行函数

1.知识点:可以对照下面的录屏进行阅读 SQL> --字符函数 SQL> --字符串的转换 SQL> select lower('hellO WORld') 转小写,upper('hellO WORld') 转大写,initcap('hello world') 首字母大写 2 from dual; SQL> --substr(a,b) 从a中,第b位开始取,取右边所有的字符 SQL> select substr('Hello World',4) from dual; SQL&