Created
May 17, 2012 11:59
-
-
Save cb372/2718416 to your computer and use it in GitHub Desktop.
Redis server in Finagle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.twitter.finagle.redis | |
import com.twitter.finagle.Service | |
import com.twitter.finagle.builder.{ServerBuilder} | |
import java.net.InetSocketAddress | |
import protocol._ | |
import collection.mutable.{ Map => MMap } | |
import java.util.concurrent.Executors | |
import com.twitter.util.{FuturePool, Future} | |
/** | |
* Author: chris | |
* Created: 5/17/12 | |
*/ | |
object Server { | |
class RedisService extends Service[Command, Reply] { | |
private val keyValues = MMap[String, Array[Byte]]() | |
private val pool = FuturePool(Executors.newFixedThreadPool(4)) | |
def apply(cmd: Command): Future[Reply] = cmd match { | |
case Get(key: String) => get(key) | |
case Set(key: String, value: Array[Byte]) => set(key, value) | |
case Del(keys: List[String]) => del(keys) | |
case Exists(key: String) => exists(key) | |
case Append(key: String, suffix: Array[Byte]) => append(key, suffix) | |
case _ => Future.exception(ServerError("Not implemented")) | |
} | |
private def get(key: String) = pool { | |
keyValues get(key) match { | |
case Some(value: Array[Byte]) => BulkReply(value) | |
case None => EmptyBulkReply() | |
} | |
} | |
private def set(key: String, value: Array[Byte]) = pool { | |
keyValues += key -> value | |
StatusReply("OK") | |
} | |
private def del(keys: List[String]) = pool { | |
val found = keyValues.filterKeys(keys.contains(_)) | |
found foreach (keyValues -= _._1) | |
IntegerReply(found.size) | |
} | |
private def exists(key: String) = pool { | |
if (keyValues contains key) | |
IntegerReply(1) | |
else | |
IntegerReply(0) | |
} | |
def append(key: String, suffix: Array[Byte]) = pool { | |
keyValues get(key) match { | |
case Some(value: Array[Byte]) => { | |
val newValue = value ++ suffix | |
keyValues += key -> newValue | |
IntegerReply(newValue.length) | |
} | |
case None => { | |
keyValues += key -> suffix | |
IntegerReply(suffix.length) | |
} | |
} | |
} | |
} | |
def main(args: Array[String]) { | |
val myService = new RedisService | |
ServerBuilder() | |
.codec(Redis()) | |
.bindTo(new InetSocketAddress(6379)) | |
.name("redisserver") | |
.build(myService) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment