如何通过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获取请求。如图

Snipaste_2020-03-01_11-16-54.png

主要是不知道okhttp和Java 8 的CompleteFuture异步方式怎么结合,麻烦各位解惑,感恩~

以上是 如何通过okHttp实现异步数据的读取 的全部内容, 来源链接: utcz.com/p/172984.html

回到顶部