Database Reference
In-Depth Information
Building Applications with ZooKeeper
Having covered ZooKeeper in some depth, let's turn back to writing some useful applica-
tions with it.
A Configuration Service
One of the most basic services that a distributed application needs is a configuration ser-
vice, so that common pieces of configuration information can be shared by machines in a
cluster. At the simplest level, ZooKeeper can act as a highly available store for configura-
tion, allowing application participants to retrieve or update configuration files. Using
ZooKeeper watches, it is possible to create an active configuration service, where interes-
ted clients are notified of changes in configuration.
Let's write such a service. We make a couple of assumptions that simplify the implementa-
tion (they could be removed with a little more work). First, the only configuration values
we need to store are strings, and keys are just znode paths, so we use a znode to store each
key-value pair. Second, there is a single client performing updates at any one time. Among
other things, this model fits with the idea of a master (such as the namenode in HDFS) that
wishes to update information that its workers need to follow.
We wrap the code up in a class called ActiveKeyValueStore :
public class ActiveKeyValueStore extends ConnectionWatcher {
private static final Charset CHARSET = Charset . forName ( "UTF-8" );
public void write ( String path , String value ) throws
InterruptedException ,
KeeperException {
Stat stat = zk . exists ( path , false );
if ( stat == null ) {
zk . create ( path , value . getBytes ( CHARSET ), Ids . OPEN_ACL_UNSAFE ,
CreateMode . PERSISTENT );
} else {
zk . setData ( path , value . getBytes ( CHARSET ), - 1 );
}
}
}
The contract of the write() method is that a key with the given value is written to
ZooKeeper. It hides the difference between creating a new znode and updating an existing
znode with a new value by testing first for the znode using the exists operation and then
performing the appropriate operation. The other detail worth mentioning is the need to con-
Search WWH ::




Custom Search