Skip to content

Instantly share code, notes, and snippets.

@mtranter
Last active February 27, 2016 17:52
Show Gist options
  • Save mtranter/8abb558e6e203df302cf to your computer and use it in GitHub Desktop.
Save mtranter/8abb558e6e203df302cf to your computer and use it in GitHub Desktop.
Save and get Json from ETCD instance
package com.trizzle.etcd
import net.nikore.etcd.EtcdClient
import net.nikore.etcd.EtcdJsonProtocol.EtcdResponse
import spray.json._
import scala.concurrent.duration.Duration
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.Manifest
import scala.util.{Failure, Try, Success}
class PimpedEtcdClient(client: EtcdClient) {
def loadAsync[TRes : Manifest : JsonReader](key: String)(implicit ctx: ExecutionContext): Future[Try[Option[TRes]]] = {
getFromEtcd(key)
}
def saveAsync[TVal : JsonWriter](key: String, value: TVal, ttl: Option[Duration] = None): Future[EtcdResponse] = {
val sval = value.toJson.toString()
client.setKey(key, sval, ttl)
}
def getFromEtcd[TVal : Manifest : JsonReader](key: String)(implicit ctx: ExecutionContext): Future[Try[Option[TVal]]] = {
client.getKey(key) map(v => {
v.node.value match {
case Some(nodeVal) => {
try {
Success(Some(nodeVal.parseJson.convertTo[TVal]))
}catch{
case ex: Throwable => Failure(ex)
}
}
case None => {
Success(None)
}
}
}) recover {
case ex: Throwable => Failure(ex)
}
}
}
object PimpedEtcdClient {
implicit def pimpMe(etcdClient: EtcdClient): PimpedEtcdClient = {
new PimpedEtcdClient(etcdClient)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment