Akka HTTP: Blocking in a future blocks the server

前端 未结 2 1942
别跟我提以往
别跟我提以往 2020-12-07 10:13

I am trying to use Akka HTTP to basic authenticate my request. It so happens that I have an external resource to authenticate through, so I have to make a rest call to this

2条回答
  •  执念已碎
    2020-12-07 10:20

    Strange, but for me everything works fine (no blocking). Here is code:

    import akka.actor.ActorSystem
    import akka.http.scaladsl.Http
    import akka.http.scaladsl.server.Directives._
    import akka.http.scaladsl.server.Route
    import akka.stream.ActorMaterializer
    
    import scala.concurrent.Future
    
    
    object Main {
    
      implicit val system = ActorSystem()
      implicit val executor = system.dispatcher
      implicit val materializer = ActorMaterializer()
    
      val routes: Route = (post & entity(as[String])) { e =>
        complete {
          Future {
            Thread.sleep(5000)
            e
          }
        }
      } ~
        (get & path(Segment)) { r =>
          complete {
            "get"
          }
        }
    
      def main(args: Array[String]) {
    
        Http().bindAndHandle(routes, "0.0.0.0", 9000).onFailure {
          case e =>
            system.shutdown()
        }
      }
    }
    

    Also you can wrap you async code into onComplete or onSuccess directive:

    onComplete(Future{Thread.sleep(5000)}){e} 
    
    onSuccess(Future{Thread.sleep(5000)}){complete(e)}
    

提交回复
热议问题