cache

Signature

def cache[K](cache: Cache[K, RouteResult], keyer: PartialFunction[RequestContext, K]): Directive0

Description

Wraps its inner Route with caching support using the given akka.http.caching.scaladsl.Cache implementation and the provided keyer function.

The directive tries to serve the request from the given cache and only if not found runs the inner route to generate a new response. A simple cache can be constructed using routeCache constructor.

The directive is implemented in terms of cachingProhibited and alwaysCache. This means that clients can circumvent the cache using a Cache-Control request header. This behavior may not be adequate depending on your backend implementation (i.e how expensive a call circumventing the cache into the backend is). If you want to force all requests to be handled by the cache use the alwaysCache directive instead. In complexer cases, e.g. when the backend can validate that a cached request is still acceptable according to the request Cache-Control header the predefined caching directives may not be sufficient and a custom solution is necessary.

Example

//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))
  PartialFunction {
    case r: RequestContext if isGet(r) && !isAuthorized(r) ⇒ r.request.uri
  }
}

var i = 0
val route =
  cache(routeCache, simpleKeyer) {
    complete {
      i += 1
      i.toString
    }
  }

Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "1"
}
// now cached
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "1"
}
// caching prevented
Get("/") ~> `Cache-Control`(`no-cache`) ~> route ~> check {
  responseAs[String] shouldEqual "2"
}
The source code for this page can be found here.