一、Zookeeper分布式锁原理
二、Zookeeper JavaAPI操作
1、Curator介绍
Curator是Apache Zookeeper的Java客户端。 常见的Zookeeper Java API: 原生Java API。 ZkClient。 Curator。 Curator项目目标是简化Zookeeper客户端的使用。 Curator最初是Netfix研发的,后来捐献了Apache基金会,目前是Apache的顶级项目。 官网:https://curator.apache.org/docs/about
2、创建节点
public class CuratorTest { private CuratorFramework client; @Beforepublic void init ( ) { // 1 、方式一RetryPolicy retryPolicy = new ExponentialBackoffRetry( 3000 , 10 ) ; CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient( "localhost:2181" , 60 * 1000 , 15 * 1000 , retryPolicy) ; // 2 、方式二CuratorFramework client = CuratorFrameworkFactory.builder( ) .connectString( "localhost:2181" ) .sessionTimeoutMs( 60 * 1000 ) .connectionTimeoutMs( 15 * 1000 ) .retryPolicy( retryPolicy) .namespace( "test" ) .build( ) ; // 开启连接client.start( ) ; this.client = client; } /*** 1 、基本创建:client.create( ) .forPath( "/app1" ) * 2 、创建节点,带有数据:client.create( ) .forPath( "/app1" , data) * 3 、设置节点的类型: client.create( ) .withMode( CreateMode.EPHEMERAL) .forPath( "/app1" ) * 4 、创建多级节点: client.create( ) .creatingParentsIfNeeded( ) .forPath( "/app1/app2" ) */@Testpublic void testCreate ( ) { // 1 、基本创建// 如果创建节点,没有指定数据,则默认将当前客户端的ip作为数据存储try { String path = client.create( ) .forPath( "/app1" ) ; System.out.println( path) ; } catch ( Exception e) { throw new RuntimeException( e) ; } } /*** 查询节点:* 1 、查询数据:get* 2 、查询子节点: ls * 3 、查询节点状态信息: ls -s */@Testpublic void testQueryData ( ) { // 1 、查询数据: gettry { byte[ ] data = client.getData( ) .forPath( "/app1" ) ; System.out.println( new String( data)) ; } catch ( Exception e) { throw new RuntimeException( e) ; } } @Testpublic void testQueryChildren ( ) { // 查询子节点: ls try { List< String> stringList = client.getChildren( ) .forPath( "/" ) ; System.out.println( stringList) ; } catch ( Exception e) { throw new RuntimeException( e) ; } } @Testpublic void testQueryState ( ) { // 查询节点状态信息: ls -s Stat status = new Stat( ) ; try { client.getData( ) .storingStatIn( status) .forPath( "/app1" ) ; System.out.println( status) ; } catch ( Exception e) { throw new RuntimeException( e) ; } } @Afterpublic void close ( ) { if ( client != null) { client.close( ) ; } }
}