Spring Bootの非同期メソッドを呼び出す方法
非同期メソッドをSpring Bootで呼び出すには、@Asyncアノテーションで非同期メソッドをマークし、そのメソッドの呼び出し時にCompletableFutureまたはFutureを返り値として使用します。以下にサンプルコードを示します。
まず、Spring Bootアプリケーションの設定クラスに@EnableAsyncアノテーションを追加して、非同期メソッドのサポートを有効化します。
@Configuration
@EnableAsync
public class AppConfig {
// 配置其他bean...
}
メソッドに非同期実行が必要な場合は、@Asyncアノテーションを追加します。
@Service
public class MyService {
@Async
public CompletableFuture<String> asyncMethod() {
// 异步执行的逻辑...
return CompletableFuture.completedFuture("异步方法执行完毕");
}
}
非同期メソッドの結果を受信するには、非同期メソッドを呼び出す場所で CompletableFuture または Future を使用します。
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/async")
public CompletableFuture<String> asyncEndpoint() {
return myService.asyncMethod();
}
}
このにより、/asyncインターフェイスを呼び出すと、非同期メソッドasyncMethodが非同期に実行され、非同期メソッドの実行結果を取得するために使用できるCompletableFutureオブジェクトが返されます。