Skip to content

Instantly share code, notes, and snippets.

@bmatheny
Created September 1, 2011 11:43
Show Gist options
  • Save bmatheny/1186011 to your computer and use it in GitHub Desktop.
Save bmatheny/1186011 to your computer and use it in GitHub Desktop.
Memcache Codec with Quit Support
import com.twitter.finagle.{Codec, Service}
import com.twitter.finagle.memcached.protocol.{Command, Response, Quit => MemcacheQuit, NoOp}
import com.twitter.finagle.memcached.protocol.text.{Encoder, Memcached, ResponseToEncoding}
import com.twitter.finagle.memcached.protocol.text.server.{Decoder => ServerDecoder, DecodingToCommand}
import com.twitter.logging.Logger
import com.twitter.util.Future
import org.jboss.netty.buffer.{ChannelBuffer, ChannelBuffers}
import org.jboss.netty.channel._
import org.jboss.netty.util.CharsetUtil
// Simple ChannelHandler that deals with the protocol specified quit message
class MemcacheChannelHandler extends SimpleChannelHandler {
override def messageReceived(ctx: ChannelHandlerContext, e: MessageEvent) {
e.getMessage() match {
case MemcacheQuit() =>
ctx.getChannel().close()
case _ => super.messageReceived(ctx, e)
}
}
}
class MemcachedQuitCodec extends Memcached {
implicit def str2cb(str: String): ChannelBuffer = ChannelBuffers.copiedBuffer(str, CharsetUtil.UTF_8)
private[this] val storageCommands = collection.Set[ChannelBuffer](
"set", "add", "replace", "append", "prepend")
override def server = Function.const {
new Codec[Command, Response] {
def pipelineFactory = new ChannelPipelineFactory {
def getPipeline() = {
val pipeline = Channels.pipeline()
pipeline.addLast("decoder", new ServerDecoder(storageCommands))
pipeline.addLast("decoding2command", new DecodingToCommand)
// NOTE This is the only change to the parent class
pipeline.addLast("handleQuitCommand", new MemcacheChannelHandler)
pipeline.addLast("encoder", new Encoder)
pipeline.addLast("response2encoding", new ResponseToEncoding)
pipeline
}
}
} // new Codec
} // server
} // class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment