scala/liftweb中使用memcached

由于在项目中需要使用有时效性的缓存,为图方便就使用了memcached,memcached有个特性就是可以设置缓存数据的时效,这个对于存放验证码等数据非常方便。当然redis也可以,根据项目需求来选择吧!

首先在build.sbt中增加

"com.googlecode.xmemcached" % "xmemcached" % "1.4.2"
这里使用的memcached客户端是
xmemcached

相关文档见: http://code.google.com/p/xmemcached/w/list


下面是简单封装MemcachedHelper

package code.lib

import net.rubyeye.xmemcached.MemcachedClient
import net.rubyeye.xmemcached.XMemcachedClientBuilder
import net.rubyeye.xmemcached.command.BinaryCommandFactory
import net.rubyeye.xmemcached.utils.AddrUtil

object MemcachedHelper extends App {
  lazy val client = initMemcachedClient()

  private def initMemcachedClient(servers: String = "localhost:11211") = {
    val builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(servers))
    //builder.setConnectionPoolSize(5)
    builder.setCommandFactory(new BinaryCommandFactory())
    builder.build()
  }

  private def checkKey(key: String) {
    require(!key.isEmpty(), "key不能为空")
  }

  def set(key: String, value: Any, exp: Int = 0): Boolean = {
    checkKey(key)
    client.set(key, exp, value)
  }

  def get(key: String): Option[Any] = {
    checkKey(key)
    Option(client.get(key))
  }

  def delete(key: String): Boolean = {
    checkKey(key)
    client.delete(key)
  }

  set("list", List(1, 2, 3, 4))
  println(get("list"))
}

这里需要注意的是,在windows平台,由于版本较旧,不支持二进制协议,运行上面的程序可能报错,可以在linux下安装新版本的memcached。


附linux下memcached的安装:

到http://memcached.org/ 下载源码包,由于memcached依赖libevent,所以还要去http://libevent.org 下载libevent源码,先安装libevent,如果已经安装可以忽略。

安装libevent

./configure --prefix=/usr/local/tools/libevent
如果装libevent安装在/usr/locap/tools/libevent,那么安装memcached使用下面的设置来安装


./configure --prefix=/usr/local/tools/memcached --with-libevent=/usr/local/tools/libevent
启动脚本(start.sh)


./memcached -d -m 64 -u root -p 11211 //根据需要修改相应参数设置 -m是指缓存内存大小。

你可能感兴趣的:(scala,memcached,xmemcached,Liftweb)