【问题标题】:Spring Boot Async ProgrammingSpring Boot 异步编程
【发布时间】:2021-05-12 10:11:45
【问题描述】:

我是软件新手。我正在努力了解 Spring Boot 中的异步编程。如上所示,我将线程池大小设置为 2。当我一次又一次地请求相同的 url 三次时。我的两个请求是异步工作的。第三个正在等待。还行吧。但是当我不使用异步功能(既不使用@async 注释也不使用线程池)时,它仍然像以前一样异步执行事务。所以我很困惑。 Spring Boot 休息控制器默认行为异步?为什么我们在 Spring Boot 中使用 @async?还是我理解错了?

@Service
public class TenantService {
    @Autowired
    private TenantRepository tenantRepository;

    @Async("threadPoolTaskExecutor")
    public Future<List<Tenant>> getAllTenants() {
        System.out.println("Execute method asynchronously - "
                + Thread.currentThread().getName());
        try {
            List<Tenant> allTenants = tenantRepository.findAll();

            Thread.sleep(5000);

            return new AsyncResult<>(allTenants);
        } catch (InterruptedException e) {
            //
        }
        return null;
    }
}
@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsynchThread-");
        executor.initialize();
        return executor;
    }

    @Bean(name = "threadPoolTaskExecutor2")
    public Executor threadPoolTaskExecutor2() {
        return new ThreadPoolTaskExecutor();
    }
}

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    我假设您使用的是 Spring Boot 中的默认嵌入式 Tomcat。如果是这样,那你就没有误会。默认情况下,Tomcat 确实会异步工作,这意味着它会为每个请求启动一个新线程(请参阅this 了解相关内容)。

    @Async 注释并非旨在替换 Tomcat 在这种情况下提供的功能。相反,该注释允许在单独的线程中执行 bean 的任何方法。对于您的特定用例,让 Tomcat 为每个请求启动一个新线程可能就足够了,但有时您可能希望进一步并行化工作。

    当一个请求必须触发一些繁重的计算,但响应不依赖于它时,您可能希望同时使用这两个示例。通过使用@Async 注解,您可以在另一个线程上启动繁重的计算,并让请求更快完成(有效地允许服务器处理其他请求,而繁重的计算在另一个线程上独立运行)。

    【讨论】:

    • 感谢您的回答。尽管我没有使用异步和线程池,但我想了解为什么 Spring boot 会以异步方式运行。我之所以学会它,是因为嵌入式 Tomcat 为请求提供了异步操作。我得到了它。那么,如果后台没有繁重的操作,只有查询数据库和返回数据的请求,我能说我不会使用Async吗?
    • 很高兴能帮上忙!除了后台的繁重操作之外,您还可以找到 Async 注释的许多其他用例。另一个示例是,对于同一个请求,您必须执行 2 个(或更多)独立的数据库查询。您可以使用 Async 并行执行所有这些查询,并在最终计算响应之前等待它们完成。
    猜你喜欢
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2019-01-09
    • 2019-09-27
    • 1970-01-01
    相关资源
    最近更新 更多