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 org.apache.commons.collections.map.LRUMap

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

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

/**
 * LRU Cache wrapping org.apache.commons.collections.map.LRUMap
 */

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")
    logger.info("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 {
      cache.get(key)
    }

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

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

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

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

}

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

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
    LRUinMemoryCache.init
  }
}

Now we are accessing in-memory cache


//Get data from Cache:
LRUinMemoryCache.get("inMemoryData")

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

//Remove data from in-memory cache
LRUinMemoryCache.delete("inMemoryData")

Advertisements
This entry was posted in Scala. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s