Created
November 13, 2014 23:41
-
-
Save inexplicable/67a759ae70c4a8f64097 to your computer and use it in GitHub Desktop.
play scala filter using rediscala async
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
name := "play-scala" | |
version := "1.0-SNAPSHOT" | |
lazy val root = (project in file(".")).enablePlugins(PlayScala) | |
scalaVersion := "2.11.1" | |
resolvers += "rediscala" at "http://dl.bintray.com/etaty/maven" | |
libraryDependencies ++= Seq( | |
jdbc, | |
anorm, | |
cache, | |
ws, | |
"com.etaty.rediscala" %% "rediscala" % "1.4.0" | |
) |
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
/** | |
* Created by huzhou on 11/13/14. | |
*/ | |
import play.api.mvc._ | |
import filters.TokenFilter | |
object Global extends WithFilters(TokenFilter) { | |
} |
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 filters | |
import play.api.Logger | |
import play.api.libs.concurrent.Akka | |
import play.api.mvc.{Filter, RequestHeader, Result} | |
import redis.RedisClient | |
import scala.concurrent.Future | |
/** | |
* Created by huzhou on 11/13/14. | |
*/ | |
object TokenFilter extends Filter { | |
def apply(nextFilter: (RequestHeader) => Future[Result]) | |
(requestHeader: RequestHeader): Future[Result] = { | |
val startTime = System.currentTimeMillis | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import play.api.Play.current | |
implicit val system = Akka.system | |
val redis = RedisClient() | |
redis.get[String]("not there yet").flatMap{acceptance => | |
acceptance match { | |
case None => | |
nextFilter(requestHeader).map { result => | |
val endTime = System.currentTimeMillis | |
val requestTime = endTime - startTime | |
Logger.info(s"${requestHeader.method} ${requestHeader.uri} " + | |
s"took ${requestTime}ms and returned ${result.header.status}") | |
result.withHeaders("Request-Time" -> requestTime.toString) | |
} | |
case Some(shouldNotBeThere) => | |
Future.failed(new IllegalStateException()) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment