SpringBootのマルチスレッドからの返り値を取得する方法
Spring Boot では、CompletableFuture を使用してマルチスレッドによる戻り値の取得を行うことができます。CompletableFuture は Java 8 で導入された非同期プログラミング向けのツールで、非同期操作の結果を処理するために使用されます。
まず、CompletableFutureオブジェクトを作成する必要があり、supplyAsyncメソッドで実行する非同期操作を指定します。supplyAsyncメソッドでは、ラムダ式を使用することで、具体的な非同期タスクを定義できます。
たとえば、時間がかかる処理を実行し、文字列結果を返したい場合は、次のように記述します:
import java.util.concurrent.CompletableFuture;
public class MyService {
public CompletableFuture<String> doAsyncOperation() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 耗时的操作
String result = "Hello World";
return result;
});
return future;
}
}
そして、そのメソッドを呼び出す場所で、CompletableFutureのgetメソッドを使って非同期操作の結果を取得できます。getメソッドはブロックする方法で、非同期操作が完了して結果が返されるまで待ちます。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/async")
public String asyncOperation() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = myService.doAsyncOperation();
String result = future.get();
return result;
}
}
上記の例では、asyncOperationメソッドがdoAsyncOperationメソッドを呼び出してCompletableFutureオブジェクトを取得しています。そのあと、getメソッドを呼び出して非同期操作の結果を取得しています。
getメソッドはInterruptedException、ExecutionExceptionなどの例外をスローする可能性があるので、例外処理を行う必要があります。
また、非同期操作の結果を処理するために CompletableFuture が提供するその他のメソッド (thenApply、thenAccept、thenCompose など) も使用できます。使用方法の詳細については、Java の公式ドキュメントを参照してください。