Database Reference
In-Depth Information
delete a znode only if the version number specified is the same as the version number of
the znode it is trying to delete — an optimistic locking mechanism that allows clients to
detect conflicts over znode modification. You can bypass the version check, however, by
using a version number of -1 to delete the znode regardless of its version number.
There is no recursive delete operation in ZooKeeper, so you have to delete child znodes
before parents. This is what we do in the
DeleteGroup
class, which will remove a
group and all its members (
Example 21-5
)
.
Example 21-5. A program to delete a group and its members
public class
DeleteGroup
extends
ConnectionWatcher
{
public
void
delete
(
String groupName
)
throws
KeeperException
,
InterruptedException
{
String path
=
"/"
+
groupName
;
try
{
List
<
String
>
children
=
zk
.
getChildren
(
path
,
false
);
for
(
String child
:
children
) {
zk
.
delete
(
path
+
"/"
+
child
, -
1
);
}
zk
.
delete
(
path
, -
1
);
}
catch
(
KeeperException
.
NoNodeException
e
) {
System
.
out
.
printf
(
"Group %s does not exist\n"
,
groupName
);
System
.
exit
(
1
);
}
}
public static
void
main
(
String
[]
args
)
throws
Exception
{
DeleteGroup deleteGroup
=
new
DeleteGroup
();
deleteGroup
.
connect
(
args
[
0
]);
deleteGroup
.
delete
(
args
[
1
]);
deleteGroup
.
close
();
}
}
Finally, we can delete the
zoo
group that we created earlier:
%
java DeleteGroup localhost zoo
%
java ListGroup localhost zoo
Group zoo does not exist