我有一個控制器:
@PostMapping("/xyz")
void getThatMessageAndEmail(@RequestBody(Integer z))
{
String messageToCatch = MG.messageGetter(z);
System.out.println(functionToConcat(z,messageToCatch));
}
還有我的服務 messageGetter,這是一個異步服務:
@Service
class MG()
{
@Async
String messageGetter(Integer z)
{
return "HELLOFRIEND";
}
}
現在,我無法在控制器中捕捉到訊息“HELLOFRIEND”。如何在控制器中捕獲訊息(messageToCatch 變數)?
uj5u.com熱心網友回復:
第一:異步方法必須是public!;-)
然后,您必須將回傳型別重構為Future<String/ CompletableFuture<String>:
@Async
public Future<String> messageGetter(Integer z)
// alternatively CompletableFuture<String> ...
{
// and provide it accordingly:
return new AsyncResult<String>("HELLOFRIEND");// or CompletableFuture.of("HELLOFRIEND");
}
在控制器中,你會:
阻止異步執行直到回傳或例外:
String messageToCatch = MG.messageGetter(z).get(); // in both cases..或(同時做某事):
Future<String> fut = MG.messageGetter(z); while (true) { if (fut.isDone()) { // done! System.out.println(functionToConcat(z, fut.get())); break; } // do something else }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360664.html
