web-services - 为 2.5.x 独立 Play WS

标签 web-services scala playframework playframework-2.5

我想在 Play 应用程序之外创建一个 Play Web 服务客户端。对于 Play WS 版本 2.4.x 很容易发现它是这样完成的:

val config = new NingAsyncHttpClientConfigBuilder().build()
val builder = new AsyncHttpClientConfig.Builder(config)
val client = new NingWSClient(builder.build)

但是在 2.5.x 中 NingWSClient现在已弃用 - 取而代之的是 AhcWSClient应该使用。

不幸的是,我没有找到一个完整的示例来解释在 Play 之外创建和使用 AhcWsClient。目前我这样做:
import play.api.libs.ws.ahc.AhcWSClient
import akka.stream.ActorMaterializer
import akka.actor.ActorSystem

implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
val ws = AhcWSClient()

val req = ws.url("http://example.com").get().map{
  resp => resp.body
}(system.dispatcher)

这是创建 AhcWsClient 的正确方法吗? ?有没有办法创建 AhcWSClient没有 ActorSystem ?

最佳答案

您可能正在使用编译时依赖注入(inject),否则您只需使用 @Inject() (ws: WSClient) , 对?。
文档中有一个示例:https://www.playframework.com/documentation/2.5.x/ScalaWS#using-wsclient
所以你可以在你的应用程序加载器中写这样的东西:

lazy val ws = {
  import com.typesafe.config.ConfigFactory
  import play.api._
  import play.api.libs.ws._
  import play.api.libs.ws.ahc.{AhcWSClient, AhcWSClientConfig}
  import play.api.libs.ws.ahc.AhcConfigBuilder
  import org.asynchttpclient.AsyncHttpClientConfig

  val configuration = Configuration.reference ++ Configuration(ConfigFactory.parseString(
    """
      |ws.followRedirects = true
    """.stripMargin))

  val parser = new WSConfigParser(configuration, environment)
  val config = new AhcWSClientConfig(wsClientConfig = parser.parse())
  val builder = new AhcConfigBuilder(config)
  val logging = new AsyncHttpClientConfig.AdditionalChannelInitializer() {
    override def initChannel(channel: io.netty.channel.Channel): Unit = {
      channel.pipeline.addFirst("log", new io.netty.handler.logging.LoggingHandler("debug"))
    }
  }
  val ahcBuilder = builder.configure()
  ahcBuilder.setHttpAdditionalChannelInitializer(logging)
  val ahcConfig = ahcBuilder.build()
  new AhcWSClient(ahcConfig)
}
applicationLifecycle.addStopHook(() => Future.successful(ws.close))

然后注入(inject)ws到您的 Controller 。我不能 100% 确定这种方法,如果一些 Play 大师可以验证这一点,我会很高兴。
关于 ActorSystem , 你只需要它来获得一个线程池来解决 Future .您也可以只导入或注入(inject)默认执行上下文:play.api.libs.concurrent.Execution.Implicits.defaultContext .
或者您可以使用自己的:implicit val wsContext: ExecutionContext = actorSystem.dispatchers.lookup("contexts.your-special-ws-config") .

关于web-services - 为 2.5.x 独立 Play WS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36568290/

相关文章:

scala - 在 Spark RDD Println Error 中,如何显示 [Ljava.lang.String;@8e6606 等数据

java - 无法连接到 grpc 服务器并获取 'First received frame was not SETTINGS'

scala - 定义 Play for Scala 中的 future 隐式上下文

wcf - 如何更好地组织 Web 服务接口(interface)

iPhone 的 PHP RESTful Web 服务

java - Main(args) 包含多个数组

scala - Akka 框架 (Scala) - 代理存储大型复杂状态

java - Play 安全!来自外部申请

c# - CXF Web 服务的 .NET 客户端身份验证和 SOAP 凭据 header

java - 将现有功能公开为 Web 服务的高效且简单的方法