我有以下基本代码来启动 akk-http 服务,我想将客户端 IP 传递到我的路由处理程序中。
...
final Flow<HttpRequest, HttpResponse, NotUsed> myFlow= myRoute().flow(actorSystem, actorMaterializer);
final CompletionStage<ServerBinding> binding = akkaHttp.bindAndHandle(myFlow,
ConnectHttp.toHost(configurationInstance.getBindAddress(), configurationInstance.getBindPort()), actorMaterializer);
...
我找到了这篇文章:
Obtaining the client IP in Akka-http
但是它使用低级 API。
到目前为止我已经得到了这个,但我不想更改为低级 API。有没有办法让它与高级 API 一起工作?我在 myRoute() 上收到编译错误,我不确定如何为此方法创建处理程序。
...
Http.get(system)
.bind(ConnectHttp.toHost(configurationInstance.getBindAddress(),
configurationInstance.getBindPort()), mat);
CompletionStage<ServerBinding> binding =
rverSource.runWith(Sink.foreach(connection -> {
connection.handleWithAsyncHandler(
myRoute(connection.remoteAddress()), mat); // ERROR
})).run(mat);
...
public Route finalRoute(InetSocketAddress client) { .... }
-- (更新)在 Stefano Bonetti 的帮助下,这才有效。
ompletionStage<ServerBinding> binding =
serverSource.to(Sink.foreach(connection -> {
connection.handleWith(MyRoute(connection.remoteAddress())
.flow(system, mat), mat);
}
)).run(mat);
最佳答案
您应该能够将 Route
转换为 Flow[HttpRequest, HttpResponse, NotUsed]
并将其传递给 handleWith
函数。
connection.handleWith(myRoute(connection.remoteAddress()).flow(actorSystem, mat), mat);
关于java - Akka-http,用Java获取客户端IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520324/