Play WS
依赖
要在项目中使用,请添加以下依赖:
- sbt
libraryDependencies += "me.yangbajing.nacos4s" %% "nacos-play-ws" % "2.0.0-SNAPSHOT"
- Maven
<dependencies> <dependency> <groupId>me.yangbajing.nacos4s</groupId> <artifactId>nacos-play-ws_3</artifactId> <version>2.0.0-SNAPSHOT</version> </dependency> </dependencies>
- Gradle
dependencies { implementation "me.yangbajing.nacos4s:nacos-play-ws_3:2.0.0-SNAPSHOT" }
使用 - 依赖注入
并在 application.conf
配置文件中启用 NacosWSModule
模块。
sourceplay.modules {
enabled += "yangbajing.nacos4s.play.ws.scaladsl.Nacos4sWSModule"
enabled += "yangbajing.nacos4s.play.ws.javadsl.Nacos4sWSModule"
}
与原生的 play-ws 使用唯一的区别就是在 Inject 时添加 @Named("nacos")
注解。
Scala API
sourceimport play.api.libs.ws.WSClient
import javax.inject.{Inject, Named}
class NacosWSClientController @Inject() (@Named("nacos") wsClient: WSClient) {
def page = {
val req = wsClient.url("http://example-service/api/health")
}
}
Java API
source
import play.libs.ws.WSClient;
import play.libs.ws.WSRequest;
import javax.inject.Inject;
import javax.inject.Named;
public class NacosWSClientController {
private final WSClient wsClient;
@Inject
public NacosWSClientController(@Named("nacos") WSClient wsClient) {
this.wsClient = wsClient;
}
public void index() {
WSRequest req = wsClient.url("http://example-service/api/health");
}
}
使用 - 手动创建
Scala API
sourceval wsClient = NacosWSClient(StandaloneAhcWSClient())
val response = wsClient.url("https://github.com/yangbajing/nacos-sdk-scala").get().futureValue
response.status shouldBe 200
wsClient.close()
Java API
sourceval ahcWSClient = new StandaloneAhcWSClient(new DefaultAsyncHttpClient(), SystemMaterializer(system).materializer)
val wsClient = new NacosWSClient(system, ahcWSClient)
val begin = System.currentTimeMillis()
val response = wsClient.url("https://github.com/yangbajing/nacos-sdk-scala").get().asScala.futureValue
val end = System.currentTimeMillis()
log.debug(s"Cost time ${end - begin}ms.")
response.getStatus shouldBe 200
wsClient.close()
2.0.0*