java - Akka-http,用Java获取客户端IP

标签 java akka-http

我有以下基本代码来启动 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/

相关文章:

java - String.Format 中的阿拉伯字符 ("%d",1,Locale.US)

java - 运行测试时 UIAutomator 错误

scala - Akka HTTP 2.0 使用 SSL (HTTPS)

akka-http - 如何链接作为函数结果的路由(使用 `~` )?

scala - akka-http 和 JsonEntityStreamingSupport

java - 将 pdf 文件加载到已构建的 jar 中

java - 在嵌入式 Jetty Web 容器中运行 OSGi 容器。可能的?

java - 如何在JSch中使用SFTP channel 执行shell命令?

scala - 使用 akka-http 重新加载静态资源

scala - 加载的 html 从父目录请求静态内容