• 聊聊、Zookeeper 客户端 Curator


    【Curator】 

     和 ZkClient 一样,Curator 也是开源客户端,Curator 是 Netflix 公司开源的一套框架。 

    <dependency>
    	<groupId>org.apache.curator</groupId>
    	<artifactId>curator-framework</artifactId>
    	<version>2.8.0</version>
    </dependency>
    

     创建连接

    •  static CuratorFramework newClient(String connectString,RetryPolicy retryPolicy)
    •  static CuratorFramework newClient(String connectString,int sessionTimeOutMs,int connectionTimeOutMs,RetryPolicy retryPolicy)

     和原生 API,ZkClient 客户端都不一样,Curator 通过 CuratorFrameworkFactory 来创建客户端,然后调用 start 方法来启动。

    package zookeeper.curator;
    
    import org.apache.curator.RetryPolicy;
    import org.apache.curator.framework.CuratorFramework;
    import org.apache.curator.framework.CuratorFrameworkFactory;
    import org.apache.curator.retry.ExponentialBackoffRetry;
    
    public class OpenCuratorClient {
    	
    	public static void main(String[] args) {
    		RetryPolicy policy = new ExponentialBackoffRetry(1000, 3);
    		CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181",5000,3000,policy);
    		client.start();
    				
    	}
    
    }
    

     ExponentialBackoffRetry 是 SleepingRetry 实现类,而 SleepingRetry 又是 RetryPolicy 接口实现类。ExponentialBackoffRetry(1000, 3) 表示初始 sleep 时间 1 秒,重试次数为 3。

     

     创建节点

    •  public CreateBuilder create()
    •  public ProtectACLCreateModePathAndBytesable<String> creatingParentsIfNeeded()
    •  public T withMode(CreateMode mode)
    •  public T forPath(String path,byte[] data) throws Exception
    •  public T forPath(String path) throws Exception
    package zookeeper.curator;
    
    import org.apache.curator.RetryPolicy;
    import org.apache.curator.framework.CuratorFramework;
    import org.apache.curator.framework.CuratorFrameworkFactory;
    import org.apache.curator.retry.ExponentialBackoffRetry;
    import org.apache.zookeeper.CreateMode;
    
    public class OpenCuratorClient {
    	
    	public static void main(String[] args) {
    		
    		RetryPolicy policy = new ExponentialBackoffRetry(1000, 3);
    		CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181",5000,3000,policy);
    		client.start();
    		
    		try {
    			
    			client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/app2","app2".getBytes());
    			
    		} catch (Exception e1) {
    			e1.printStackTrace();
    		}
    		
    		
    		try {
    			Thread.sleep(Integer.MAX_VALUE);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		
    	}
    
    }
    

      

     谢谢大家观看!

  • 相关阅读:
    基础系列(3)—— 高级数据类型
    ASP.NET MVC5 基础系列(3)——视图
    JSP学习笔记
    Tomcat学习笔记
    Tomcat学习笔记
    Tomcat学习笔记
    Tomcat学习笔记
    Tomcat学习笔记
    MySQL学习笔记(5)
    MySQL学习笔记(4)
  • 原文地址:https://www.cnblogs.com/xums/p/7220493.html
Copyright © 2020-2023  润新知