首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Spring Boot中编写CompletableFuture循环(在for循环中调用)?

在Spring Boot中编写CompletableFuture循环,可以通过以下步骤实现:

  1. 首先,确保你的Spring Boot项目中已经引入了CompletableFuture的依赖。可以在pom.xml文件中添加以下依赖:
代码语言:txt
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-async</artifactId>
</dependency>
  1. 在你的Spring Boot应用程序中,创建一个方法来执行异步操作。可以使用@Async注解来标记该方法为异步方法。例如:
代码语言:txt
复制
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Async
    public CompletableFuture<String> doSomethingAsync(int i) {
        // 异步操作的逻辑
        // 返回一个CompletableFuture对象
    }
}
  1. 在调用该异步方法的地方,使用CompletableFuture的allOf方法来等待所有异步操作完成。可以使用一个List来保存所有的CompletableFuture对象,并在循环中调用异步方法。例如:
代码语言:txt
复制
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class MyController {

    @Autowired
    private MyService myService;

    @GetMapping("/async")
    public void doAsync() throws ExecutionException, InterruptedException {
        List<CompletableFuture<String>> futures = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            CompletableFuture<String> future = myService.doSomethingAsync(i);
            futures.add(future);
        }

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        allFutures.get(); // 等待所有异步操作完成
    }
}

在上述代码中,我们创建了一个List来保存所有的CompletableFuture对象,然后在循环中调用异步方法,并将返回的CompletableFuture对象添加到List中。最后,使用CompletableFuture.allOf方法等待所有异步操作完成。

这样,你就可以在Spring Boot中编写CompletableFuture循环了。请注意,上述代码仅为示例,实际使用时需要根据具体业务逻辑进行调整。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券