我有以下一段代码来自官方的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();
    }
}


现在,我有一个处理传入套接字消息的套接字参与者。我想在每次有新消息通过套接字时都触发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
    }
}

最佳答案

您必须像在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();
    }
}


如果存在不允许您使用此问题的问题(例如,您不控制演员的创建方式),请向问题中添加更多信息。

09-11 03:08
查看更多