WS in Play 变得难以置信的复杂 2.6.X

WS in Play become incredible complex for 2.6.X

Play 2.3.X WS 模块非常容易使用:

WS.url(s"http://$webEndpoint/hand/$handnumber").get()

这么简单明了的用法。

在 Play 2.6.x 根据 link : https://www.playframework.com/documentation/2.6.x/JavaWS 您需要先创建一个http客户端。

WSClient customWSClient = play.libs.ws.ahc.AhcWSClient.create(
    play.libs.ws.ahc.AhcWSClientConfigFactory.forConfig(
            configuration.underlying(),
            environment.classLoader()),
            null, // no HTTP caching
            materializer);

更重要的是,你还需要一个实体化器和一个支持实体化器的akka​​系统。

String name = "wsclient";
ActorSystem system = ActorSystem.create(name);
ActorMaterializerSettings settings =       ActorMaterializerSettings.create(system);
ActorMaterializer materializer = ActorMaterializer.create(settings, system, name);
// Set up AsyncHttpClient directly from config
AsyncHttpClientConfig asyncHttpClientConfig = new  DefaultAsyncHttpClientConfig.Builder()
    .setMaxRequestRetry(0)
    .setShutdownQuietPeriod(0)
    .setShutdownTimeout(0).build();
AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(asyncHttpClientConfig);

// Set up WSClient instance directly from asynchttpclient.
WSClient client = new AhcWSClient(
asyncHttpClient,
materializer

);

我知道它会为 WS 客户端添加更多功能,但是当我只想要一个简单的 http 客户端时,使用变得无法接受复杂,它是如此有线。

您 link 访问的页面显示:

We recommend that you get your WSClient instances using dependency injection as described above. WSClient instances created through dependency injection are simpler to use because they are automatically created when the application starts and cleaned up when the application stops.

手动创建 WSClient 的实例很乏味,您应该不会感到惊讶。

同一页面描述了如何使用 WSClient 的注入版本:

import javax.inject.Inject;

import play.mvc.*;
import play.libs.ws.*;
import java.util.concurrent.CompletionStage;

public class MyClient implements WSBodyReadables, WSBodyWritables {
    private final WSClient ws;

    @Inject
    public MyClient(WSClient ws) {
        this.ws = ws;
    }
    // ...
}

这和以前的版本一样简单。实际上,在以前的 Play 版本中,您还可以创建 WSClient 的自定义实例,并且它曾经具有相当的复杂性(modulo Akka 东西)。

最后我使用 ScalaJ-http,https://github.com/scalaj/scalaj-http

哪个好用:

import scalaj.http._
...
response= Http("http://localhost:5000/health").asString

在play 2.3.6中哪个简单如WS

对于 Play 2.6.x 框架可能不会为您创建默认 ws,请参阅 https://github.com/playframework/play-scala-tls-example/blob/2.6.x/app/Main.scala

的示例

对于使用完全支持 DI 的 Scala Play 的人来说,创建 WSClient 实例的一种解决方案是 Play.current.injector.instanceOf[WSClient]。这在更新到 Scala Play 2.6 时也很有用,只需进行一些小的更改而不向所有添加 DI 支持。