Skip to content

Instantly share code, notes, and snippets.

@sudix
Created September 13, 2012 05:54
Show Gist options
  • Save sudix/3712184 to your computer and use it in GitHub Desktop.
Save sudix/3712184 to your computer and use it in GitHub Desktop.
Scalaでmemched繋ぎたいけどmemcached落ちててもエラーにならないようにするコード。動いてるけどまったくScalaらしくないのでなんとかしたい。
import net.rubyeye.xmemcached._
object Memcache {
def apply(host: String, port: Int): Memcache = {
val mc = new Memcache
mc.connect(host, port)
mc
}
}
class Memcache {
private var client: XMemcachedClient = null
def connect(host: String, port: Int): Unit = {
try {
client = new XMemcachedClient(host, port)
} catch {
case e: Exception => {
println("memcached connect error host:%s port:%d".format(host, port))
}
}
}
/**
* This function returns true if a key exists on memcached
*/
def exists(key: String): Boolean = {
try {
if(client == null) {
false
} else {
Option(client.get[Any](key)) match {
case None => false
case _ => true
}
}
} catch {
case e: Exception => {
println("memcached get error error=%s".format(e.toString))
false
}
}
}
def close(): Unit = {
if(client != null && !client.isShutdown) {
client.shutdown
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment