/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
- package org.act
- import akka.actor.ActorSystem
- import akka.http.scaladsl.Http
- import akka.http.scaladsl.marshalling.ToResponseMarshallable
- import akka.http.scaladsl.server.Directives._
- import akka.kafka.ConsumerSettings
- import akka.kafka.Subscriptions.assignment
- import akka.kafka.scaladsl.Consumer
- import akka.stream.ActorMaterializer
- import de.heikoseeberger.akkasse.ServerSentEvent
- import org.apache.kafka.clients.consumer.ConsumerConfig
- import org.apache.kafka.common.TopicPartition
- import org.apache.kafka.common.serialization.StringDeserializer
- import scala.concurrent.duration.{Duration, MINUTES}
- import scala.io.StdIn
- object Server extends App {
- implicit val system = ActorSystem("server")
- implicit val materialiser = ActorMaterializer()
- implicit val executionContext = system.dispatcher
- val consumerSettings: ConsumerSettings[String, String] = ConsumerSettings(
- system,
- new StringDeserializer,
- new StringDeserializer
- )
- .withBootstrapServers("kafka-0.broker:9092")
- .withGroupId("g1")
- .withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
- val route = path("all") {
- import de.heikoseeberger.akkasse.EventStreamMarshalling._
- get {
- complete(ToResponseMarshallable(Consumer.plainSource(
- consumerSettings,
- assignment(new TopicPartition("crimes", 0)))
- .map(record => record.value())
- .map(value => ServerSentEvent(value, "crime"))
- .keepAlive(Duration(20, MINUTES), () => ServerSentEvent.Heartbeat)))
- }
- }
- val serverBinding = Http().bindAndHandle(route, "localhost", 8091)
- StdIn.readLine()
- serverBinding
- .flatMap(_.unbind())
- .onComplete(_ => system.terminate())
- }