这篇文章将为大家详细讲解有关ZooKeeper Java客户端API如何更新数据,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
同步更新数据
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
public class SetData_API_Sync_Usage implements Watcher {
private static CountDownLatch connectedSemaphore = new CountDownLatch(1);
private static ZooKeeper zk = null;
public static void main (String[] args) throws Exception{
String path = "/titush-book2";
zk = new ZooKeeper("202.201.*.*:2100",
5000,
new SetData_API_Sync_Usage());
connectedSemaphore.await();
zk.create(path, "1231".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.getData(path, true, null);
Stat stat = zk.setData(path, "4561".getBytes(), -1);
System.out.println(stat.getCzxid()+","+stat.getMzxid()+","+stat.getVersion());
Stat stat2 = zk.setData(path, "4561".getBytes(), stat.getVersion());
System.out.println(stat2.getCzxid()+","+stat2.getMzxid()+","+stat2.getVersion());
try{
zk.setData(path, "456".getBytes(), stat.getVersion());
} catch ( KeeperException e) {
System.out.println("Error:" + e.code() + "," + e.getMessage());
}
Thread.sleep( Integer.MAX_VALUE);
}
@Override
public void process(WatchedEvent event) {
if (KeeperState.SyncConnected == event.getState()) {
if (EventType.None == event.getType() && null == event.getPath()) {
connectedSemaphore.countDown();
}
}
}
}
结果打印
111,112,1
111,113,2
Error:BADVERSION,KeeperErrorCode = BadVersion for /titush-book2
数据节点的当前最新版本表示为 -1,第一版本表示为 0。
第一次设置数据后版本更新为 1,第二次设置后版本更新为 2。
第三次用版本 1 去更新时出现错误,因为此时的版本已经为 2 了。
这里就是乐观锁的使用,stat.getVersion()
用来进行写入校验。
关于ZooKeeper Java客户端API如何更新数据就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。