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

时间:2017-10-11 08:10:39

标签: scala playframework ws-client scala-2.12

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

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

对于这种简单而明确的用法。

根据链接在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);

而且,你还需要一个物化器和一个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客户端时,使用情况就变得复杂了,它是如此有线。

3 个答案:

答案 0 :(得分:4)

您链接的页面显示:

  

我们建议您使用依赖注入来获取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;
    }
    // ...
}

这很简单,就像以前的版本一样。实际上,在之前的Play版本中,您也可以创建WSClient的自定义实例,并且过去具有相似的复杂性(模数Akka的东西)。

答案 1 :(得分:0)

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

这很容易使用:

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

这就像WS in play 2.3.6一样简单

对于Play 2.6.x,框架可能无法为您创建默认的ws并查看https://github.com/playframework/play-scala-tls-example/blob/2.6.x/app/Main.scala的示例

答案 2 :(得分:0)

对于使用具有完全DI支持的Scala Play的人来说,创建WSClient实例的一种解决方案是Play.current.injector.instanceOf[WSClient]。在不做任何改动就向Scala Play 2.6进行升级而又不向所有人添加DI支持的情况下,这也很有用。