2016-04-15 23 views
0

有沒有辦法將javadsl Route轉換爲Flow?在Scala中我們有隱式的handlerFlow,但在Java中我們沒有類似的東西。將路線轉換爲Java的Akka-Http中的流程

試圖調用handlerFlow,但它使用了scaladsl類型並且與javadsl版本的Route不兼容。

我想使用低級版本的API來綁定到http和https,並且能夠訪問連接。

==========================
更新: 我以前的想法從svezfaz的答案,現在我得到的代碼:

Flow<HttpRequest, HttpResponse, NotUsed> createFlow(ActorSystem system, Materializer mat) { 
    scala.Function1<akka.http.scaladsl.server.RequestContext, scala.concurrent.Future<akka.http.scaladsl.server.RouteResult>> r = RouteImplementation.apply(createRoute()); 
    Flow f = RouteResult$.MODULE$.route2HandlerFlow(
     r, 
     RoutingSettings$.MODULE$.apply(system), 
     ParserSettings$.MODULE$.apply(system), 
     mat, 
     RoutingLog$.MODULE$.fromActorSystem(system), 
     null, 
     RejectionHandler$.MODULE$._mthdefault(), 
     null 
    ).asJava(); 
    return f; 
} 

它看起來是正確的,但它不能編譯。可能,我必須將Scala庫包含到classpath中。然後與其他Scala-to-Java類型的轉換一起工作。

我認爲它更容易重寫它不帶Java路由。

回答

0

在阿卡-HTTP 10.0.6,您可以使用

akka.http.scaladsl.server.Route.handlerFlow(route: Route): Flow[HttpRequest, HttpResponse, NotUsed] 

有需要一些implicits,但它們很容易進入範圍。

1

你可以從akka.http.javadsl.server.HttpServiceBase獲取靈感(見下文)。 使用RouteImplementation將javadsl轉換爲scaladsl,然後調用route2HandlerFlow轉換爲流。

/** 
    * Uses the route to handle incoming connections and requests for the ServerBinding. 
    */ 
    def handleConnectionsWithRoute(interface: String, port: Int, route: Route, system: ActorSystem, materializer: Materializer): CompletionStage[ServerBinding] = { 
    implicit val s = system 
    implicit val m = materializer 

    import system.dispatcher 
    val r: server.Route = RouteImplementation(route) 
    Http(system).bind(interface, port).toMat(Sink.foreach(_.handleWith(akka.http.scaladsl.server.RouteResult.route2HandlerFlow(r))))(Keep.left).run()(materializer).toJava 
    }