java Sping Boot :@Async无法正常工作

pwuypxnk  于 2023-11-15  发布在  Java
关注(0)|答案(3)|浏览(144)

如果之前有人遇到过这个问题;我有一个版本为2.1.1.RELEASE的springboot应用程序;在这个应用程序中,我有一个控制器,它调用一个调用电子邮件服务的服务,所以关系就像控制器-> businessLogicService -> emailService
在emailService中,我用@Async标记了sendMail方法,并通过在主应用程序中放置@EnableAsync来启用它
当前,该方法仍在主线程上运行,该主线程阻塞该操作直到其完成。
我已经深入调查了这个问题,但仍然没有运气。
我做过的一个奇怪的练习;是克隆3个服务,但这次@Async工作正常,所以不知何故,其他服务出现了问题
请记住,应用程序是巨大的,电子邮件服务在很多地方都是自动连接的,对于bussinessLogicService来说也是如此。

nlejzf6q

nlejzf6q1#

请尝试将以下配置类添加到您的应用程序,并告诉它是否工作:

/**
 * 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();
    }

}

字符串

c3frrgcw

c3frrgcw2#

在同一个类中调用@Async方法是行不通的,你必须从不同的类中调用该方法。

nfs0ujit

nfs0ujit3#

如果EmailService有一个sendMail方法,该方法是baseC,则应该直接在businessLogicService类方法中调用它。

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

字符串
如果在businessLogicService中调用了其他方法,请尝试使用该方法。

相关问题