Database Reference
In-Depth Information
KeeperException
{
byte
[]
data
=
zk
.
getData
(
path
,
watcher
,
null
/*stat*/
);
return new
String
(
data
,
CHARSET
);
}
The
getData()
method of ZooKeeper takes the path, a
Watcher
, and a
Stat
object.
The
Stat
object is filled in with values by
getData()
and is used to pass information
back to the caller. In this way, the caller can get both the data and the metadata for a
znode, although in this case, we pass a
null Stat
because we are not interested in the
metadata.
iveKeyValueStore
and, after starting, calls the store's
read()
method (in its
dis-
playConfig()
method) to pass a reference to itself as the watcher. It displays the ini-
tial value of the configuration that it reads.
Example 21-7. An application that watches for updates of a property in ZooKeeper and
prints them to the console
public class
ConfigWatcher
implements
Watcher
{
private
ActiveKeyValueStore store
;
public
ConfigWatcher
(
String hosts
)
throws
IOException
,
InterruptedException
{
store
=
new
ActiveKeyValueStore
();
store
.
connect
(
hosts
);
}
public
void
displayConfig
()
throws
InterruptedException
,
KeeperException
{
String value
=
store
.
read
(
ConfigUpdater
.
PATH
,
this
);
System
.
out
.
printf
(
"Read %s as %s\n"
,
ConfigUpdater
.
PATH
,
value
);
}
@Override
public
void
process
(
WatchedEvent event
) {
if
(
event
.
getType
() ==
EventType
.
NodeDataChanged
) {
try
{
displayConfig
();
}
catch
(
InterruptedException e
) {
System
.
err
.
println
(
"Interrupted. Exiting."
);
Thread
.
currentThread
().
interrupt
();
}
catch
(
KeeperException e
) {
System
.
err
.
printf
(
"KeeperException: %s. Exiting.\n"
,
e
);
}