Spring boot:@Async 无法正常工作

问题描述 投票:0回答:3

如果有人以前遇到过这个问题; 我有一个版本为 2.1.1.RELEASE 的 springboot 应用程序; 在这个应用程序中 我有一个控制器,它调用一项服务,该服务调用电子邮件服务 所以关系就像 控制器 -> 业务逻辑服务 -> 电子邮件服务

在 emailService 中,我有带有 @Async 标记的 sendMail 方法 我通过将 @EnableAsync 放入主应用程序来启用它

当前该方法仍在主线程上运行,该线程会阻塞操作直到完成。

我已经深入研究了这个问题,但仍然没有运气

我做过的奇怪练习之一;就是克隆3个服务 但这一次 @Async 工作得很好 所以其他的有点问题

考虑到应用程序很大,并且电子邮件服务在很多地方都自动连接,对于 BusinessLogicService 来说也是如此

java spring-boot asynchronous
3个回答
0
投票

请尝试将以下配置类添加到您的应用程序中并判断它是否有效:

/**
 * Enables asynchronous task management. Implements {@link AsyncConfigurer} to allow
 * event publishing operations being executed both synchronously and asynchronously.
 */
@EnableAsync
@Configuration(proxyBeanMethods = false)
public class AsyncConfig implements AsyncConfigurer {

    /*
     * Implementing AsyncConfigurer allows to determine an Executor for asynchronous operations only. This way it is
     * sufficient to simply annotate desired methods with @Async for async treatment, event publishing tasks included.
     *
     * In contrast, providing an ApplicationEventMulticaster would cause all event publishing tasks to be executed
     * asynchronously by default. To be able to execute synchronous tasks nevertheless, we would have to adapt
     * ApplicationEventMulticaster#multicastEvent() accordingly: for example, we could decide by means of a marker
     * interface to which executor the task should get passed (https://stackoverflow.com/a/57929153).
     */

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(8);
        taskExecutor.setMaxPoolSize(32);
        taskExecutor.setQueueCapacity(64);
        taskExecutor.setThreadNamePrefix("DallasMultipassExecutor-");
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}

0
投票

从同一个类中调用 @Async 方法将不起作用,您必须从不同的类中调用该方法。


0
投票

如果EmailService有一个异步方法sendMail,则应该直接在businessLogicService类方法中调用它。像这样的东西

BusinessLogicService { 
  foo(){
   emailService.sendMail();
  }
}

如果在businessLogicService 中调用其他方法,请尝试使其异步。

© www.soinside.com 2019 - 2024. All rights reserved.