zookeeper 客户端提示:instance must be started before calling this method

今天开始使用Curator ZooKeeper开源客户端。由于ZooKeeper原生的客户端比较低层,而且使用起来不方便,Netflix公司对ZooKeeper客户端API进行了封闭,提供一可以替代原生ZooKeeper客户端的框架——Curator,刚学习Curator,正尝试使用Curator编写znode节点的增、删、改、查,真是万事开头难,执行实例时就报错:java.lang.IllegalStateException: instance must be started before calling this method。

解决思路:

1、使用CuratorFramework的工厂函数生成客户端;

 2、在操作ZK之前,记得先对客户端执行start(),启动客户端实例;

 3、在操作ZK完成后,关闭客户端——close()。

 

核心代码:

	public FileComponent(String zkServers, String root) {
		this.root = root;
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
		zkClient =   CuratorFrameworkFactory.builder()
                .connectString(zkServers)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .namespace(root)
                .build();
		
		try {
			init();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 初始数据方法
	@SuppressWarnings({ "resource", "unused" })
	public void init() throws Exception {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xml);
		String[] names = applicationContext.getBeanDefinitionNames();

		int totalSize = names.length;
		int pageSize = 2;
		pageCount = (totalSize + pageSize - 1) / pageSize;

		for (int i = 0; i < pageCount; i = i + 2) {

			// 创建根节点的临时节点
			if(zkClient.getState() != CuratorFrameworkState.STARTED){
				zkClient.start();
			}
			zkClient.create().withMode(CreateMode.EPHEMERAL).forPath("/" + names[i + 1], names[i].getBytes());
			
			// 内存临时缓存
			if (!list.contains(names[i + 1])) {
				list.add(names[i + 1]);
			}
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值