Apache ZooKeeper
medium 30 minZooKeeper is a small, replicated, strictly ordered tree of notes that programs use to coordinate: who is the leader, who is alive, who holds a lock, what the settings are.
A tiny tree with sessions and watches
Read it, run it, change a line and run it again.
Loading editor…
A single-process model of sessions, ephemeral sequential nodes and one-time watches, with the election recipe on top. No consensus here.
The same in Java
// 1. The native client: wait for the connection event, do not spinCountDownLatch connected = new CountDownLatch(1);ZooKeeper zk = new ZooKeeper("zk1:2181,zk2:2181,zk3:2181", 30000, e -> { if (e.getState() == Watcher.Event.KeeperState.SyncConnected) connected.countDown();});connected.await();// Parents must exist. Use real ACLs in production instead of OPEN_ACL_UNSAFE.zk.create("/config", "v1".getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);zk.create("/services", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);zk.create("/services/host-1", "10.0.0.5:80".getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);// Read and watch. Read again inside the handler.Stat stat = new Stat();byte[] data = zk.getData("/config", event -> { if (event.getType() == Watcher.Event.EventType.NodeDataChanged) reloadConfig();}, stat);// Change only if nobody else did (compare and set)try { zk.setData("/config", "v2".getBytes(UTF_8), stat.getVersion());} catch (KeeperException.BadVersionException e) { // read again and retry}// 2. Apache Curator, the recommended layerCuratorFramework client = CuratorFrameworkFactory.builder() .connectString("zk1:2181,zk2:2181,zk3:2181") .sessionTimeoutMs(30000) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build();client.start();client.blockUntilConnected();LeaderSelector selector = new LeaderSelector(client, "/leader", new LeaderSelectorListenerAdapter() { @Override public void takeLeadership(CuratorFramework c) throws Exception { doLeaderWork(); // interrupted on SUSPENDED or LOST; returning gives up the lead }});selector.autoRequeue();selector.start();InterProcessMutex lock = new InterProcessMutex(client, "/locks/order-123");if (lock.acquire(10, TimeUnit.SECONDS)) { try { processOrder(); } finally { lock.release(); }}ServiceDiscovery<InstanceDetails> discovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class) .client(client).basePath("/services").thisInstance(instance).build();discovery.start(); // registers this instanceThe same in Go
conn, _, err := zk.Connect([]string{"zk1:2181", "zk2:2181", "zk3:2181"}, 30*time.Second)if err != nil { log.Fatal(err)}defer conn.Close()data, stat, changed, err := conn.GetW("/config")if err != nil { log.Fatal(err)}fmt.Println(string(data), stat.Version)<-changed // fires once: call GetW againThe same in Shell
# Python client (kazoo) re-registers for you:# from kazoo.client import KazooClient# zk = KazooClient(hosts="zk1:2181,zk2:2181,zk3:2181"); zk.start()# @zk.DataWatch("/config")# def on_change(data, stat): print(data)bin/zkCli.sh -server localhost:2181# ls /services# get -s /config# create -e /services/host-2 "10.0.0.6:80"# get -w /config# sync /config# Diagnostics. Only srvr works until you extend the whitelist in zoo.cfg:# 4lw.commands.whitelist=srvr,stat,mntr,ruok,dumpecho srvr | nc localhost 2181 # role, latency, countsecho mntr | nc localhost 2181 # metricsecho ruok | nc localhost 2181 # answers imok: running, not proof of a quorumecho dump | nc localhost 2181 # sessions and ephemeral nodes, on the leadercurl http://localhost:8080/commands/monitor