WS in Play对于2.6.X变得异常复杂

whe*_*rby 4 scala playframework ws-client scala-2.12

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

WS.url(s"http://$webEndpoint/hand/$handnumber").get()
Run Code Online (Sandbox Code Playgroud)

对于这种简单而直接的用法。

在Play 2.6.x中,根据链接: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);
Run Code Online (Sandbox Code Playgroud)

而且,您还需要一个实现器和一个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
Run Code Online (Sandbox Code Playgroud)

);

我知道它将为WS客户端添加更多功能,但是当我只想要一个简单的http客户端时,用法变得难以接受,它是如此连接。

Has*_*tor 5

您链接到的页面显示:

我们建议您如上所述使用依赖项注入来获取WSClient实例。通过依赖关系注入创建的WSClient实例使用起来更简单,因为它们在应用程序启动时自动创建,并在应用程序停止时清理。

然后,手动创建的实例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;
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这和以前的版本一样简单。实际上,在以前的Play版本中,您还可以创建的自定义实例WSClient,而该实例过去具有相当的复杂性(模数Akka的东西)。

  • 不,如果使用依赖注入,则无需创建WSClient的自定义实例。它将由Play框架为您创建。它与Play 2.3中的内容几乎相同,不同之处在于您不使用静态工厂,而是使用依赖项注入。 (2认同)