Zookeeper开发总结 授权与验证 自动重连 递归删除 事务

Zookeeper开发小结

一.实例化zookeeper与自动重连代码样例

<span style="font-size:18px;">public class ZkClient {

    private ZooKeeper zooKeeper;

    private String connectString;
    private Integer sessionTimeout;

    private Object <span style="color:#ff0000;"><strong>waiter = new Object();//simple object-lock</strong>
</span>    //"zk-client.properties";//classpath下
    public ZkClient(String configLocation) throws  Exception{
        Properties config = new Properties();
        config.load(ClassLoader.getSystemResourceAsStream(configLocation));
        connectString = config.getProperty("zk.connectString");
        if(connectString == null){
            throw new NullPointerException("'zk.connectString' cant be empty.. ");
        }
        sessionTimeout = Integer.parseInt(config.getProperty("zk.sessionTimeout","-1"));
        connectZK();
    }

    /**
     * core method,启动zk服务 本实例基于自动重连策略<span style="color:#ff0000;"><strong>,如果zk连接没有建立成功或者在运行时断开,将会自动重连.
     */</strong>
</span>    private void connectZK() {
</span>
<span style="font-size:18px;">//<span style="font-size:18px;">private Object <span style="color:#ff0000;background-color: rgb(240, 240, 240);"><strong>waiter = new Object();//simple object-lock</strong></span></span></span>
<span style="font-size:18px;">        synchronized (waiter) {
            try {
                SessionWatcher watcher =<span style="color:#ff0000;"><strong> new SessionWatcher();</strong>
</span>                // session的构建是异步的
                this.zooKeeper = new ZooKeeper(connectString, sessionTimeout, watcher, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
            <span style="color:#ff0000;"><strong>waiter.notifyAll();</strong>
</span>        }
    }


    class SessionWatcher implements Watcher {

        public void process(WatchedEvent<strong> event)</strong> {
            // 如果是“数据变更”事件
            if (event.getType() != Event.EventType.None) {
                return;
            }

            <span style="color:#ff0000;"><strong>// 如果是链接状态迁移
            // 参见keeperState
            synchronized (waiter) {</strong>
</span>                switch (event.getState()) {
                    // zk连接建立成功,或者重连成功
                    case SyncConnected:
                        System.out.println("Connected...");
                        waiter.notifyAll();
                        break;
                    // session过期,这是个非常严重的问题,有可能client端出现了问题,也有可能zk环境故障
                    // 此处仅仅是重新实例化zk client
                    case Expired:
                        System.out.println("Expired...");
                        // 重连
                        connectZK();
                        break;
                    // session过期
                    case Disconnected:
                        // 链接断开,或session迁移
                        System.out.println("Connecting....");
                        break;
                    case AuthFailed:
                        close();
                        throw new RuntimeException("ZK Connection auth failed...");
                    default:
                        break;
                }
            }
        }
    }

    private void close(){
        try {
            synchronized (waiter) {
                if (this.zooKeeper != null) {
                    zooKeeper.close();
                }
                waiter.notifyAll();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
</span>

二.授权与验证

<span style="font-size:18px;">String auth = "admin:admin";
//anywhere,but before znode operation
//can addauth more than once
zooKeeper.addAuthInfo("digest", auth.getBytes("UTF-8"));</span>

 

<span style="font-size:18px;">Id id = new Id("digest", DigestAuthenticationProvider.generateDigest(auth));
ACL acl = new ACL(ZooDefs.Perms.ALL, id);
List<ACL> acls = Collections.singletonList(acl);
//如果不需要访问控制,可以使用acls = ZooDefs.Ids.OPEN_ACL_UNSAFE
zooKeeper.create("/singleWorker", null, acls, CreateMode.PERSISTENT);</span>

三.创建znode节点

<span style="font-size:18px;">try{
	Id id = new Id("digest", DigestAuthenticationProvider.generateDigest(auth));
	ACL acl = new ACL(ZooDefs.Perms.ALL, id);
	List<ACL> acls = Collections.singletonList(acl);
	zooKeeper.create("/workers", null, acls, CreateMode.PERSISTENT);
}catch(KeeperException.NodeExistsException e){
	//在并发环境中,节点创建有可能已经被创建,即使使用exist方法检测也不能确保.
} catch (Exception e){
	e.printStackTrace();
}</span>

四.删除节点

<span style="font-size:18px;">//zookeeper不允许直接删除含有子节点的节点;
//如果你需要删除当前节点以及其所有子<span style="color:#ff0000;"><strong>节点,需要递归来做</strong>
</span>private void deletePath(String path,ZooKeeper zooKeeper) throws Exception{
	List<String> children = zooKeeper.getChildren(path,false);
	for(String child : children){
		<strong><span style="color:#ff0000;">String childPath = path + "/" + child;
		deletePath(childPath,zooKeeper);
</span></strong>	}
	try{
	 zooKeeper.delete(path,-1);
	}catch(KeeperException.NoNodeException e){
		//ignore
	}
}</span>
<span style="font-size:18px;">//删除节点,删除时比较version,避免删除时被其他client修改
public boolean delete(String path){
	try{
		Stat stat = zooKeeper.exists(path,false);
		//如果节点已经存在
		if(stat != null){
			zooKeeper.delete(path,stat.getVersion());
		}
	}catch(KeeperException.NoNodeException e){
		//igore
	}catch (Exception e){
		e.printStackTrace();
                return false;
	}
	return true;
}</span>

五.修改数据

<span style="font-size:18px;">public boolean update(String path,byte[] data){
	  try{
		  Stat stat = zooKeeper.exists(path,false);
		  //如果节点已经存在
		  if(stat != null){
			  zooKeeper.setData(path,data,stat.getVersion());
			  return true;
		  }
	  }catch (KeeperException.NoNodeException e){
		   //ignore
	  }catch (Exception e){
		  e.printStackTrace();
	  }
	return false;
}</span>

五.事务

<span style="font-size:18px;">public boolean create(String name){
	try{
		Transaction tx = zooKeeper.transaction();
		tx.create("/workers/servers/" + name,null, ZooDefs.Ids.OPEN_ACL_UNSAFE,null);
		tx.create("/workers/schedule/" + name,null, ZooDefs.Ids.OPEN_ACL_UNSAFE,null);
		tx.commit();
		return true;
	} catch (Exception e){
		e.printStackTrace();
	}
	return false;
}
</span>

    备注:zookeeper中的watcher机制非常好,但是重要的数据变更,不能完全依赖watcher通知,因为对于zkClient而言,网络异常都将会导致watcher有丢失的潜在风险,而且watcher是"即发即失",当你接收到watcher通知之后,在处理过程中,数据仍然有变更的可能,因此在时间线上,不可能做到完全准确.       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值