Liftweb: Implement cache

In this blog post, I will explain how to integrate cache on server.
Liftweb Framework provide nice way to implement cache to store data(objects) on server so all user can access that data. Lift uses the LRU Cache wrapping

Create Object for handling cache operations like create,get,update and delete the data from in-memory cache.

import net.liftweb.util.{ LRU, Props }
import net.liftweb.common._

 * LRU Cache wrapping

object LRUinMemoryCache extends LRUinMemoryCache

class LRUinMemoryCache extends LRUCache[String] with Loggable {

  def size: Int = 10

  def loadFactor: Box[Float] = Empty

*Here we are setting the data in-memory cache
  def init: Unit = {
    set("inMemoryData", "here you can put whatever you want")"cache created")

//size - the maximum number of Elements allowed in the LRU map
trait LRUCache[V] extends Loggable {

  def size: Int

  def loadFactor: Box[Float]

  private val cache: LRU[String, V] = new LRU(size, loadFactor)

  def get(key: String): Box[V] =
    cache.synchronized {

  def set(key: String, data: V): V = cache.synchronized {
    cache(key) = data

def update(key: String, data: V): V = cache.synchronized {
    cache.update(key, data)

  def has(key: String): Boolean = cache.synchronized {

  def delete(key: String) = cache.synchronized(cache.remove(key))


Create and store the data in in-memory cache at the deployment time:

package bootstrap.liftweb

import code.lib.LRUinMemoryCache

 * A class that's instantiated early and run.  It allows the application
 * to modify lift's environment
class Boot {
  def boot {
    //Init the in-memory cache

Now we are accessing in-memory cache

//Get data from Cache:

//Update in-memory cache
LRUinMemoryCache.update("inMemoryData","Updated data has been set")

//Remove data from in-memory cache

This entry was posted in Scala. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s