sourceimport akka.http.scaladsl.server.directives.CachingDirectives._
import akka.http.scaladsl.server.RequestContextimport akka.http.scaladsl.model.Uriimport akka.http.scaladsl.model.headers.{Authorization,`Cache-Control`}import akka.http.scaladsl.model.headers.CacheDirectives.`no-cache`//Example keyer for non-authenticated GET requests
val simpleKeyer:PartialFunction[RequestContext,Uri]={
val isGet:RequestContext=>Boolean= _.request.method == GET
val isAuthorized:RequestContext=>Boolean=
_.request.headers.exists(_.is(Authorization.lowercaseName))
val result:PartialFunction[RequestContext,Uri]={case r:RequestContextif isGet(r)&&!isAuthorized(r)=> r.request.uri
}
result
}// Created outside the route to allow using// the same cache across multiple calls
val myCache = routeCache[Uri]var i =0
val route =
path("cached"){
alwaysCache(myCache, simpleKeyer){
complete {
i +=1
i.toString
}}}Get("/cached")~> route ~> check {
responseAs[String] shouldEqual "1"}// now cachedGet("/cached")~> route ~> check {
responseAs[String] shouldEqual "1"}Get("/cached")~>`Cache-Control`(`no-cache`)~> route ~> check {
responseAs[String] shouldEqual "1"}