alwaysCache
Signature
def alwaysCache[K](cache: Cache[K, RouteResult], keyer: PartialFunction[RequestContext, K]): Directive0
Description
Like cache but disregards a Cache-Control
request header.
Example
- Scala
-
source
import akka.http.scaladsl.server.directives.CachingDirectives._ import akka.http.scaladsl.server.RequestContext import akka.http.scaladsl.model.Uri import 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: RequestContext if 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 cached Get("/cached") ~> route ~> check { responseAs[String] shouldEqual "1" } Get("/cached") ~> `Cache-Control`(`no-cache`) ~> route ~> check { responseAs[String] shouldEqual "1" }
- Java