scala/liftweb中使用memcached

因爲在項目中須要使用有時效性的緩存,爲圖方便就使用了memcached,memcached有個特性就是能夠設置緩存數據的時效,這個對於存放驗證碼等數據很是方便。固然redis也能夠,根據項目需求來選擇吧! linux

首先在build.sbt中增長 redis

"com.googlecode.xmemcached" % "xmemcached" % "1.4.2"
這裏使用的memcached客戶端是
xmemcached

相關文檔見: http://code.google.com/p/xmemcached/w/list windows


下面是簡單封裝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。 ruby


附linux下memcached的安裝: memcached

http://memcached.org/ 下載源碼包,因爲memcached依賴libevent,因此還要去http://libevent.org 下載libevent源碼,先安裝libevent,若是已經安裝能夠忽略。 ui

安裝libevent google

./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是指緩存內存大小。
相關文章
相關標籤/搜索