Database Reference
In-Depth Information
vert the string value to a byte array, for which we just use the
getBytes()
method with
a UTF-8 encoding.
To illustrate the use of the
ActiveKeyValueStore
, consider a
ConfigUpdater
class that updates a configuration property with a value. The listing appears in
Example 21-6. An application that updates a property in ZooKeeper at random times
public class
ConfigUpdater
{
public static final
String PATH
=
"/config"
;
private
ActiveKeyValueStore store
;
private
Random random
=
new
Random
();
public
ConfigUpdater
(
String hosts
)
throws
IOException
,
InterruptedException
{
store
=
new
ActiveKeyValueStore
();
store
.
connect
(
hosts
);
}
public
void
run
()
throws
InterruptedException
,
KeeperException
{
while
(
true
) {
String value
=
random
.
nextInt
(
100
) +
""
;
store
.
write
(
PATH
,
value
);
System
.
out
.
printf
(
"Set %s to %s\n"
,
PATH
,
value
);
TimeUnit
.
SECONDS
.
sleep
(
random
.
nextInt
(
10
));
}
}
public static
void
main
(
String
[]
args
)
throws
Exception
{
ConfigUpdater configUpdater
=
new
ConfigUpdater
(
args
[
0
]);
configUpdater
.
run
();
}
}
The program is simple. A
ConfigUpdater
has an
ActiveKeyValueStore
that
connects to ZooKeeper in the
ConfigUpdater
's constructor. The
run()
method loops
forever, updating the
/config
znode at random times with random values.
Next, let's look at how to read the
/config
configuration property. First, we add a read
method to
ActiveKeyValueStore
:
public
String
read
(
String path
,
Watcher watcher
)
throws
InterruptedException
,