我从定义客户端类的官方Play 2.6文档中获取以下代码,
import javax.inject.Inject;
import play.libs.ws.*;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CompletionStage;
public class MyClient implements WSBodyReadables, WSBodyWritables {
private WSClient ws;
@Inject
public MyClient(WSClient ws) {
this.ws = ws;
sendRequest();
}
public void sendRequest() {
WSRequest request = ws.url("http://example.com");
WSRequest complexRequest = request.addHeader("headerKey", "headerValue")
.setRequestTimeout(Duration.of(1000, ChronoUnit.MILLIS))
.addQueryParameter("paramKey", "paramValue");
CompletionStage<? extends WSResponse> responsePromise = complexRequest.get();
}
}
现在我有一个处理传入套接字消息的套接字actor。我想在每次通过套接字发送新消息时触发HTTP请求。
我的问题是我不知道如何初始化MyClient类以使用其sendRequest方法。
public void onReceive(Object message) throws Exception {
if (message instanceof String) {
out.tell("I received your message: " + message, self());
MyClient a = new MyClient(); //problem here
}
}
答案 0 :(得分:1)
你必须注射它,就像你在MyClass
中所做的那样:
public class MyActor extends UntypedAbstractActor {
private MyClient client;
@Inject
public MyActor(MyClient client) {
this.client = client;
}
@Override
public void onReceive(Object message) throws Exception {
client.sendRequest();
}
}
如果有一些问题不允许你使用它(例如,你不控制演员的创建方式),请在你的问题中添加更多信息。