Created
February 26, 2014 21:14
-
-
Save dbalduini/9238721 to your computer and use it in GitHub Desktop.
A Play Framework CachPlugin implementation for Redis. @see https://github.com/debasishg/scala-redis-nb
This file contains 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 plugins | |
import play.api.Application | |
import play.api.cache.CachePlugin | |
import play.api.cache.CacheAPI | |
import play.Play.{application => App} | |
import scala.concurrent.Await | |
import scala.concurrent.duration.DurationInt | |
import com.redis.RedisClient | |
class RedisCachePlugin(app: Application) extends CachePlugin { | |
lazy val cache = new RedisCacheAPI(App.configuration().getString("app.name").toLowerCase) | |
override def enabled = App.configuration().getString("cache.redis.plugin") != "disabled" | |
override def onStart { | |
cache | |
} | |
lazy val api: CacheAPI = cache | |
} | |
class RedisCacheAPI(name: String) extends CacheAPI { | |
val host = App.configuration().getString("cache.redis.host") | |
val port = App.configuration().getInt("cache.redis.port") | |
implicit val system = akka.actor.ActorSystem("redis-client") | |
implicit val executionContext = system.dispatcher | |
implicit val timeout = akka.util.Timeout(5 seconds) | |
private val client = RedisClient(host, port) | |
def set(key: String, value: Any, expiration: Int): Unit = { | |
set(key, value) | |
if (expiration > 0) client.expire(rkey(key), expiration) | |
} | |
def set(key: String, value: Any) { | |
val newKey = rkey(key) | |
client.set(newKey, value.toString) | |
} | |
def get(key: String): Option[String] = { | |
val newKey = rkey(key) | |
Await.result(client.get(newKey), 1 second) | |
} | |
def remove(key: String): Unit = { | |
client.del(rkey(key)) | |
} | |
def rkey(key: String) = s"$name:$key:cache" | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment