Last active
December 23, 2015 08:59
-
-
Save wingchen/6611568 to your computer and use it in GitHub Desktop.
A little in memory cache that cleans itself and limit the the max size with AKKA.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.attlin.web.cache | |
| import scala.collection.mutable.HashMap | |
| import _root_.scala._ | |
| import java.util.Date | |
| import akka.actor.Actor | |
| import akka.actor.Props | |
| import scala.concurrent.duration._ | |
| import org.apache.commons.lang.time.DateUtils | |
| object AttlinInMemoryCache extends Actor { | |
| lazy val cache = HashMap[String, TimedItem]() | |
| lazy val maxCapicity = 100 | |
| def get(key: String): Option[Any] = { | |
| cache.synchronized { | |
| cache.get(key) match { | |
| case Some(TimedItem(value, _)) => Some(value) | |
| case _ => None | |
| } | |
| } | |
| } | |
| def set(key: String, item: Any, expirationInMins: Option[Int]): Any = cache.synchronized { | |
| expirationInMins match { | |
| case Some(mins) => cache(key) = TimedItem(item, DateUtils.addMinutes(new Date, mins)) | |
| case _ => cache(key) = TimedItem(item, DateUtils.addMinutes(new Date, 30)) | |
| } | |
| item | |
| } | |
| def delete(key: String) { | |
| cache.synchronized(cache.remove(key)) | |
| } | |
| def receive = { | |
| case ScheduledClean => { | |
| val time = new Date | |
| if (cache.size > maxCapicity) { | |
| // purging the cache | |
| cache.drop(cache.size - maxCapicity) | |
| } | |
| cache.keys.foreach(x => { | |
| val expirationTime = cache(x).expirationTime | |
| if (time.after(expirationTime)) { | |
| this.delete(x) | |
| } | |
| }) | |
| } | |
| } | |
| } | |
| case class TimedItem(value: Any, expirationTime: Date) | |
| case object ScheduledClean | |
| //...Initialize the cache when loading... | |
| val system = ActorSystem("Attlin") | |
| val cacheClean = system.actorOf(Props(AttlinInMemoryCache), name = "cacheClean") | |
| system.scheduler.schedule(10 minutes, 5 minutes, cacheClean, ScheduledClean) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment