如何解决在任务仍在运行时返回结果
我有一个方法需要调用后立即返回结果,即使这个方法中的所有任务都没有完成。
在这种情况下:
第 2 步是我要返回的内容,而第 3 步是我返回第 3 步后希望继续在后台运行的内容。
我不确定要采取什么方向来协调这些事件。以下是我的方法,不确定如何处理 addressRegistrationService.watchAndTransact(userAddresses);
任务。可能需要一整天才能完成,用户需要返回存款地址才能存入资金。
@PostMapping("/registeraddress")
public ResponseEntity<Mono<UserAddressesDTO>> addUserAddress(@RequestBody UserAddresses userAddresses) throws Exception {
log.info("Registering {} with addresses {}",userAddresses.getAccountId(),userAddresses.getAddresses());
//Checking if we can use the user provided addresses and account id
if (addressRegistrationService.isRegistrationValid(userAddresses)) {
throw new InvalidAddressException("Address is invalid");
}
log.info("Deposit Address is {}",generateJobcoinAddress.generateJobcoinAddress());
//Generate the deposit address and add it the UserAddress
String depositAddress = generateJobcoinAddress.generateJobcoinAddress();
//Add input and deposit address to the object
UserAddressesDTO userAddressesDTO = new UserAddressesDTO(userAddresses.getAccountId(),depositAddress,userAddresses.getAddresses());
//Request the Jobcoin Service to start watching for the transaction
//Once Jobcoin Service detects it will post the transaction to the house account
//then to the user addresses - > we will be notified separately once this is complete
addressRegistrationService.watchAndTransact(userAddresses);
//Store addresses in database,calls the data-service to store these details
return ResponseEntity.ok().body(addressRegistrationService.saveAddressDB(userAddressesDTO));
}
解决方法
您可以使用 CompletableFuture
。所以你的代码看起来像......
CompletableFuture.runAsync(() -> addressRegistrationService.watchAndTransact(userAddresses));
它将在不同的线程中运行您的 watchAndTransact
方法。并且主线程不会等待结果。所以基本上它会在后台运行。
注意:但万一失败,您将不知道发生了什么。因此,您可以添加一些自定义指标和日志。这可以是服务本身的一部分。
CompletableFuture.runAsync(() -> {
try {
addressRegistrationService.watchAndTransact(userAddresses);
// Notify user
} catch (RuntimeException e) {
// custom metrics implementation here
// log error here
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。