Skip to content

Instantly share code, notes, and snippets.

@ericacm
Created August 25, 2012 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericacm/3467868 to your computer and use it in GitHub Desktop.
Save ericacm/3467868 to your computer and use it in GitHub Desktop.
Auto Updating Caching System - CacheSystem
class CacheSystem(name: String, updateIntervalMin: Int,
cacheManager: CacheManager) {
var caches = List.empty[Cache]
val actorSystem = ActorSystem("cache_" + name)
val DEFAULT_TTL_SEC = 86400 // 1 day
def addCache(name: String, size: Int,
ttlSeconds: Int = DEFAULT_TTL_SEC): Cache = {
val config = new CacheConfiguration(name, size)
config.setTimeToIdleSeconds(ttlSeconds)
val cache = new Cache(config)
cacheManager.addCache(cache)
caches = cache :: caches
cache
}
def createCacheActor(cacheName: String, cacheSize: Int,
scheduleDelay: Duration,
actorCreator: (Cache, CacheSystem) => Actor,
ttlSeconds: Int = DEFAULT_TTL_SEC): ActorRef = {
val cache = addCache(cacheName, cacheSize, ttlSeconds)
val actor = actorSystem.actorOf(Props(actorCreator(cache, this)),
name = cacheName + "CacheActor")
actorSystem.scheduler.schedule(scheduleDelay,
updateIntervalMin minutes,
actor, UpdateCacheForNow)
if (!DateUtil.isNowInActiveBusinessDay) {
actorSystem.scheduler.scheduleOnce(scheduleDelay, actor,
UpdateCacheForPreviousBusinessDay)
}
actor
}
def findCachedObject[T](key: String, cache: Cache,
finder: () => T): Option[T] = {
val element = cache.get(key)
if (element == null) {
findObjectForCache(key, cache, finder)
} else {
Some(element.getObjectValue.asInstanceOf[T])
}
}
def findObjectForCache[T](key: String, cache: Cache,
finder: () => T): Option[T] = {
val domainObj = finder()
if (domainObj != null) {
val element = new Element(key, domainObj)
cache.put(element)
Some(domainObj)
} else {
None
}
}
def clearAllCaches() {
caches.foreach(_.removeAll())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment