Category Archives: cache

Play Framework (4) – EHCache Configuration

In fact, play framework already supports cache by EHCache. You just need to add cache in build.sbt .

libraryDependencies ++= Seq(
  cache
}

And then you can use Cache in your .scala code.

import play.api.cache.Cache
import play.api.Play.current
def itemBased(company: String, id: String) = Action {
  request =>
  try {
      val cacheKey = "itemBased"
      val cacheResult = Cache.getAs[Map[String, Array[String]]](cacheKey)
      if (!cacheResult.isDefined) {
        play.Logger.info("cache missing")
        Cache.set(cacheKey, "test")
        Ok("testok")
      }
      else {
        play.Logger.info("itemBased hit cache")
        Ok("testbad")
      }
  } catch {
      case e: IOException =>
        InternalServerError("IO Error: " + e.getMessage)
  }
}

But if you want to define your own EHCache configuration, you need to add ehcache.xml under conf/ folder of your Play application. Here is an example of simple configuration for EHCache.

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd" updateCheck="false">
<!-- This is a default configuration for 256Mb of cached data using the JVM's heap, but it must be adjusted according to specific requirement and heap sizes -->
  <defaultCache
        maxBytesLocalHeap="256000000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="false"
        maxElementsOnDisk="10000000"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU"
  />
</ehcache>

Also, if you want to do more special configurations, you need to read EHCache online document first.

Advertisements