zookeeper是树形的目录服务,每个节点都被称为ZNode,每个节点都会保存自己的数据和节点信息
节点可以拥有子节点,也允许少量数据存储在该节点下
节点分为四大类
PERSISTENT持久化节点
EPHEMERAL 临时节点: -e
PERSISTENT_SEQUENTIAL 持久化顺序节点: -s
EPHEMERAL_SEQUENTIAL临时顺序节点: -es
服务端命令
./zkServer.sh start 开启
./zkServer.sh stop 停止
./zkServer.sh status 查看状态
./zkServer.sh restart 重启
客户端命令
./zkCli.sh
ls / 查看根节点下的节点
ls /dubbo 查看根节点下dubbo节点下的节点
create默认是持久化的节点
create /app1 在根节点下创建app1节点
get /app1 获取数据
set /app1 [数据] 设置节点的数据
delete /app1 删除节点
create /app1/p1
delete all /app1 删除带有子节点的节点
zookeeper的三种Watcher
NodeCache 只监听某一个特定的节点
PathChildrenCache 监控一个Znode的子节点
TreeCache 监控整个树上的所有节点,
curator Java Api操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| CuratorFramework client;
@BeforeAll public void test() { RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
client = CuratorFrameworkFactory.builder() .connectString("localhost:2181") .retryPolicy(retryPolicy) .namespace("zlq") .build(); client.start(); }
@AfterAll public void close() { if (client != null) { client.close(); } }
@Test public void createNode() { try { client.create().withMode(CreateMode.EPHEMERAL).forPath("/p3"); Thread.sleep(20 * 1000); } catch (Exception e) { e.printStackTrace(); } }
@Test public void createmoreNode() { try { client.create().creatingParentsIfNeeded().forPath("/p3/p3.1"); } catch (Exception e) { e.printStackTrace(); } }
@Test public void getNode() throws Exception { byte[] data = client.getData().forPath("/p1"); System.out.println(new String(data)); }
@Test public void getchildren() throws Exception { List<String> list = client.getChildren().forPath("/"); System.out.println(list); }
@Test public void getstatus() throws Exception { Stat stat = new Stat(); byte[] bytes = client.getData().storingStatIn(stat).forPath("/"); System.out.println("-------------------------"); System.out.println(new String(bytes)); System.out.println("-------------------------");
}
@Test public void setData() throws Exception { Stat stat = new Stat(); client.getData().storingStatIn(stat).forPath("/p1"); int version = stat.getVersion(); client.setData().withVersion(version).forPath("/p1", "xiugai3".getBytes()); }
@Test public void delNode() throws Exception { client.delete().forPath("/p1"); }
@Test public void delallNode() throws Exception { client.delete().deletingChildrenIfNeeded().forPath("/p3"); }
|