如何通过okHttp实现异步数据的读取
我希望结合Java 8的CompleteFuture特性,编写一个okHttp异步抓取网络数据,并输出到服务端。
@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"));
//建立HTTP请求
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);
}
}
这个是源代码,我希望greeting里面提取到的数据可以与最后
CompletableFuture<List<StatusCode>> f =
client.writeValues(nodeIds, ImmutableList.of(dv));
实现数据同步,但是实际执行起来是先并行写入,然后再是从http获取请求。如图
主要是不知道okhttp和Java 8 的CompleteFuture异步方式怎么结合,麻烦各位解惑,感恩~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论