有一个资源需要通过 REST API 分几个阶段从该资源中接收数据。在第一次请求之后,会发出一个令牌,之后需要每隔一段时间发出请求,检查数据是否准备好。
关键是如何在数据就绪检查之间实现暂停。到目前为止,我还没有找到比 更好的东西Thread.sleep();,但解决方案不是很好。另一方面,您不想连续发送请求,考虑到处理时间长达 20 分钟,而且您不想让人们去处分。
对于发送请求,我使用springframework.web.client.RestTemplate
到目前为止,调用看起来像这样:
private RestClient restClient;
public String get(Phone phone) {
int counter = 0;
String status = restClient.getStatus(phone.getActivationId());
while (!status.contains("STATUS_ACCESS") && counter++ < 500) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
status = restClient.getStatus(phone.getActivationId());
}
restClient.setStatus(phone.getActivationId(), DONE);
return status.contains("STATUS_ACCESS") ? status.split(":")[1] : "ERR";
}
在 RestClient 内部:
private RestTemplate restTemplate = new RestTemplate();
public String getStatus(String activationId) {
String url = ...
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
return entity.getBody();
}
也许有一些方法可以处理RestTemplate这种情况。这Thread.sleep对我来说看起来很可怕。或不?在没有拐杖的情况下通常如何完成?
嗯,如果你有Spring,那么检查可以作为一个任务(Task)发出。你知道,Spring 中有这样的机制。更多细节与示例here