/kafkaStreamsModelServer/src/main/scala/com/lightbend/scala/kafkastreams/queriablestate/inmemory/RestServiceInMemory.scala

https://github.com/lightbend/kafka-with-akka-streams-kafka-streams-tutorial · Scala · 57 lines · 39 code · 9 blank · 9 comment · 0 complexity · 404906ef3bd46c03167ee40cd05b3722 MD5 · raw file

  1. package com.lightbend.scala.kafkastreams.queriablestate.inmemory
  2. import akka.actor.ActorSystem
  3. import akka.http.scaladsl.Http
  4. import akka.http.scaladsl.server.Directives._
  5. import akka.http.scaladsl.server.Route
  6. import akka.stream.ActorMaterializer
  7. import akka.util.Timeout
  8. import com.lightbend.scala.kafkastreams.store.StoreState
  9. import de.heikoseeberger.akkahttpjackson.JacksonSupport
  10. import org.apache.kafka.streams.KafkaStreams
  11. import com.lightbend.scala.modelServer.model.ModelToServeStats
  12. import scala.concurrent.duration._
  13. /**
  14. * A simple REST proxy that runs embedded in the Model server. This is used to
  15. * demonstrate how a developer can use the Interactive Queries APIs exposed by Kafka Streams to
  16. * locate and query the State Stores within a Kafka Streams Application.
  17. * @see https://github.com/confluentinc/examples/blob/3.2.x/kafka-streams/src/main/java/io/confluent/examples/streams/interactivequeries/WordCountInteractiveQueriesRestService.java
  18. */
  19. object RestServiceInMemory{
  20. implicit val system = ActorSystem("ModelServing")
  21. implicit val materializer = ActorMaterializer()
  22. implicit val executionContext = system.dispatcher
  23. implicit val timeout = Timeout(10.seconds)
  24. val host = "127.0.0.1"
  25. val port = 8888
  26. val routes: Route = QueriesResource.storeRoutes()
  27. // Surf to http://localhost:8888/state/instances for the list of currently deployed instances.
  28. // Then surf to http://localhost:8888/state/value for the current state of execution for a given model.
  29. def startRestProxy(streams: KafkaStreams, port: Int) = {
  30. Http().bindAndHandle(routes, host, port) map
  31. { binding => println(s"Starting models observer on port ${binding.localAddress}") } recover {
  32. case ex =>
  33. println(s"Models observer could not bind to $host:$port - ${ex.getMessage}")
  34. }
  35. }
  36. }
  37. // Surf to http://localhost:8888/state/value
  38. object QueriesResource extends JacksonSupport {
  39. def storeRoutes(): Route =
  40. get {
  41. pathPrefix("state") {
  42. path("value") {
  43. val info: ModelToServeStats = StoreState().currentState.getOrElse(ModelToServeStats.empty)
  44. complete(info)
  45. }
  46. }
  47. }
  48. }