我正在使用一个名为 milo 的库,它使用 Java 8 属性进行编程,就像使用 CompletableFuture 一样。
现在我想使用 OkHttp 从 REST 中获取数据。但我不知道如何使用 CompletableFuture 实现这一点。下面是我的代码
@Override
public void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception {
// synchronous connect
client.connect().get();
List<NodeId> nodeIds = ImmutableList.of(new NodeId(2, "HelloWorld/ScalarTypes/Int32"));
OkHttpClient okHttpClient = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url("http://localhost:8080/greeting");
for (int i = 0; i < 10; i++) {
Request request = requestBuilder.build();
Call call= okHttpClient.newCall(request);
final GreetingModel[] greetingModel = {new GreetingModel()};
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
logger.error("Writing is wrong");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String json = response.body().string();
logger.info("Connecting is good");
greetingModel[0] = JSON.parseObject(json, GreetingModel.class);
}
});
Variant v = new Variant(greetingModel[0].getId());
// don't write status or timestamps
DataValue dv = new DataValue(v, null, null);
// write asynchronously....
CompletableFuture<List<StatusCode>> f =
client.writeValues(nodeIds, ImmutableList.of(dv));
// ...but block for the results so we write in order
List<StatusCode> statusCodes = f.get();
StatusCode status = statusCodes.get(0);
if (status.isGood()) {
logger.info("Wrote '{}' to nodeId={}", v, nodeIds.get(0));
}
}
future.complete(client);
}
}
结果如图所示。写入操作在从okhttp获取数据之前。 结果