Browse Source

Load fortunes template on startup to avoid expensive modification (#4143)

timestamp checks performed by scalate cache.
Declare a marshaller instead of directly constructing HttpResponse, to
achieve more idiomatic akka-http code style.
Rafał Sumisławski 6 years ago
parent
commit
0930c048d9

+ 0 - 3
frameworks/Scala/akka-http/src/main/scala/com/typesafe/akka/http/benchmark/App.scala

@@ -21,8 +21,5 @@ class App extends Infrastructure with RandomGenerator with MySqlDataStore with P
   val executionContext: ExecutionContext = system.dispatcher
   val materializer: Materializer = ActorMaterializer()
   val appConfig: Config = ConfigFactory.load
-
-  def layout(uri: String, attributes: Map[String, Any], extraBindings: Traversable[Binding]): String =
-    templateEngine.layout(uri, attributes, extraBindings)
 }
 

+ 2 - 2
frameworks/Scala/akka-http/src/main/scala/com/typesafe/akka/http/benchmark/Templating.scala

@@ -1,7 +1,7 @@
 package com.typesafe.akka.http.benchmark
 
-import org.fusesource.scalate.Binding
+import org.fusesource.scalate.TemplateEngine
 
 trait Templating {
-  def layout(uri: String, attributes: Map[String, Any] = Map.empty, extraBindings: Traversable[Binding] = Nil): String
+  def templateEngine: TemplateEngine
 }

+ 12 - 8
frameworks/Scala/akka-http/src/main/scala/com/typesafe/akka/http/benchmark/handlers/FortunesHandler.scala

@@ -1,5 +1,6 @@
 package com.typesafe.akka.http.benchmark.handlers
 
+import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
 import akka.http.scaladsl.model.HttpCharsets._
 import akka.http.scaladsl.model.MediaTypes._
 import akka.http.scaladsl.model._
@@ -8,21 +9,24 @@ import akka.http.scaladsl.server.Route
 import com.typesafe.akka.http.benchmark.Infrastructure
 import com.typesafe.akka.http.benchmark.Templating
 import com.typesafe.akka.http.benchmark.datastore.DataStore
-
-import scala.concurrent.Future
+import com.typesafe.akka.http.benchmark.entity.Fortune
 
 trait FortunesHandler { _: Infrastructure with DataStore with Templating =>
+
   def fortunesEndpoint: Route =
     get {
       path("fortunes") {
-        complete(response)
+        onSuccess(getFortunes)(complete(_))
       }
     }
 
-  def response: Future[HttpResponse] =
-    getFortunes.map {
-      fortunes =>
-        val body = layout("/templates/fortunes.mustache", Map("fortunes" -> fortunes))
-        HttpResponse(StatusCodes.OK, entity = HttpEntity(body).withContentType(`text/html`.withCharset(`UTF-8`)))
+  private implicit lazy val fortunesMarshaller: ToEntityMarshaller[Seq[Fortune]] = {
+    val fortunesTemplate = templateEngine.load("/templates/fortunes.mustache")
+    Marshaller.opaque { fortunes =>
+      HttpEntity(
+        contentType = `text/html`.withCharset(`UTF-8`),
+        string = templateEngine.layout("", fortunesTemplate, Map("fortunes" -> fortunes))
+      )
     }
+  }
 }