Skip to content

Instantly share code, notes, and snippets.

@feliperazeek
Created June 16, 2012 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save feliperazeek/2942661 to your computer and use it in GitHub Desktop.
Save feliperazeek/2942661 to your computer and use it in GitHub Desktop.
ZooKeeper wrapper written in Scala
package com.klout.playful2.zookeeper
import com.twitter.zookeeper.ZooKeeperClient
import org.apache.zookeeper.CreateMode
import com.klout.playful2.sugar.{ config, please }
/**
* This is a simple library to add, set, delete and watch ZooKeeper nodes
*
* @author Felipe Oliveira [@_felipera]
*/
object Shelves {
/**
* Location of the ZK server(s)
*/
lazy val hosts = config string "zookeeper.hosts" !
lazy val zk = new ZooKeeperClient(hosts)
/**
* This is gonna create a new node on ZooKeeper
*/
def add(path: String, value: String, createMode: CreateMode) = zk create (path, value.getBytes, createMode)
/**
* This is gonna update the value of a node on ZooKeeper
*/
def set(path: String, value: String) = zk set (path, value.getBytes)
/**
* Deletes a node on ZooKeeper
*/
def delete(path: String) = zk delete path
/**
* Gets the value of the node
*/
def get(path: String) = zk get path
/**
* Callback
*/
def on(path: String)(runnable: NodeStatusChange => Unit) = {
zk watchNode (path, {
(data: Option[Array[Byte]]) =>
data match {
case Some(d) if d.isEmpty =>
please log "Node [%s] changed to be empty".format(path)
runnable(NodeUpdated(None))
case Some(d) =>
val value = new String(d)
please log "Node [%s] updated: %s".format(path, value)
runnable(NodeUpdated(Option(value)))
case None =>
please log "Node [%s] deleted!".format(path)
runnable(NodeDeleted)
}
})
}
}
sealed trait NodeStatusChange
case object NodeDeleted extends NodeStatusChange
case class NodeUpdated(maybeValue: Option[String]) extends NodeStatusChange
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment