/apps/crime-locator/src/main/scala/org/act/Server.scala

https://gitlab.com/rafasf/streaming-playground · Scala · 52 lines · 44 code · 8 blank · 0 comment · 0 complexity · afdafd3b773451059624ee20c0a8ac4d MD5 · raw file

  1. package org.act
  2. import akka.actor.ActorSystem
  3. import akka.http.scaladsl.Http
  4. import akka.http.scaladsl.marshalling.ToResponseMarshallable
  5. import akka.http.scaladsl.server.Directives._
  6. import akka.kafka.ConsumerSettings
  7. import akka.kafka.Subscriptions.assignment
  8. import akka.kafka.scaladsl.Consumer
  9. import akka.stream.ActorMaterializer
  10. import de.heikoseeberger.akkasse.ServerSentEvent
  11. import org.apache.kafka.clients.consumer.ConsumerConfig
  12. import org.apache.kafka.common.TopicPartition
  13. import org.apache.kafka.common.serialization.StringDeserializer
  14. import scala.concurrent.duration.{Duration, MINUTES}
  15. import scala.io.StdIn
  16. object Server extends App {
  17. implicit val system = ActorSystem("server")
  18. implicit val materialiser = ActorMaterializer()
  19. implicit val executionContext = system.dispatcher
  20. val consumerSettings: ConsumerSettings[String, String] = ConsumerSettings(
  21. system,
  22. new StringDeserializer,
  23. new StringDeserializer
  24. )
  25. .withBootstrapServers("kafka-0.broker:9092")
  26. .withGroupId("g1")
  27. .withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
  28. val route = path("all") {
  29. import de.heikoseeberger.akkasse.EventStreamMarshalling._
  30. get {
  31. complete(ToResponseMarshallable(Consumer.plainSource(
  32. consumerSettings,
  33. assignment(new TopicPartition("crimes", 0)))
  34. .map(record => record.value())
  35. .map(value => ServerSentEvent(value, "crime"))
  36. .keepAlive(Duration(20, MINUTES), () => ServerSentEvent.Heartbeat)))
  37. }
  38. }
  39. val serverBinding = Http().bindAndHandle(route, "localhost", 8091)
  40. StdIn.readLine()
  41. serverBinding
  42. .flatMap(_.unbind())
  43. .onComplete(_ => system.terminate())
  44. }