@EnableAsync 注解应该放在哪里

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

我需要以异步方式发送电子邮件,同时将数据保存到数据库中。

我的做法是这样的。

//I have tried with service layer annotating.But not worked. 
@EnableAsync 
class MyService{
 public String saveMethod(List listOfData){
    mail.sendEmailQuote(listOfData);
    mail.sendEmailWorkflowTaskAssignment(listOfData);
    myDao.saveData(listOfData);
 }
}

我需要以@Async方式执行以下方法。我应该在哪里放置 @EnableAsync 注释。这不是与时间表相关的事情。当用户单击“保存”按钮时会发生这种情况。应用中使用的是柔性弹簧blazeDS。没有我自己写的控制器。

我在代码中使用了 @Async 注释来实现以下 2 个方法。那些在课堂上打电话邮件。

@Async
sendEmailQuote(listOfData){}

@Async
sendEmailWorkflowTaskAssignment(listOfData){}

你能帮我找到应该把 @EnableAsync 放在哪里吗?

我参考这个样本

java spring asynchronous blazeds
3个回答
23
投票

EnableAsync
用于配置并启用Spring的异步方法执行能力,它不应该放在你的
Service
Component
类上,它应该放在你的
Configuration
类上,例如:

@Configuration
@EnableAsync
public class AppConfig {

}

或者对您的

AsyncExecutor
进行更多配置,例如:

@Configuration
@EnableAsync
public class AppConfig implements AsyncConfigurer {

 @Override
 public Executor getAsyncExecutor() {
     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
     executor.setCorePoolSize(7);
     executor.setMaxPoolSize(42);
     executor.setQueueCapacity(11);
     executor.setThreadNamePrefix("MyExecutor-");
     executor.initialize();
     return executor;
 }
 }

请参阅它的java文档了解更多详情。

对于您遵循的教程,

EnableAsync
放在
Application
类之上,其中
extends AsyncConfigurerSupport
具有 AsyncExecutor 配置:

@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("GithubLookup-");
    executor.initialize();
    return executor;
}
}

18
投票

只需确保 @Async 方法不是由同一个类调用即可。代理的自调用不起作用。


0
投票

让我们介绍一下 @EnableAsync 与 @Async 和执行器框架的一些用例。

您可以在任何 configuration (@Configuration) 类以及 Application(@SpringBootApplication) 的主类/驱动程序类中使用 @EnableAsync

@EnableAsync: 它指示 Spring Boot 为所有这些方法启用异步行为。

@Async: 该注解一般用在方法上,其中包含与异步任务相关的逻辑,如发送电子邮件、OTP、服务消息等。该方法通常是被注解的任何服务或类的一部分带有 @Service 或 @Component 注解。

Executor框架:一般我们更喜欢使用Executor框架来维护线程及其生命周期(创建,任务分配等)

您可以创建一个ThreadPoolTaskExecutor的Bean,并可以设置所需的属性,例如核心池大小,最大池大小,任务队列容量,可以设置用于跟踪的线程前缀,设置拒绝处理程序(拒绝条目的例外)队列中的)。检查下面的片段。

@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(4); //Generally it should higher than core pool size
    executor.setQueueCapacity(400);
    executor.setThreadNamePrefix("Executor-Thread");
    executor.setRejectedExecutionHandler((r, exception)->sysout("Thread Queue is Full."));
    executor.initialize();
    return executor;
}

希望这些信息对您有帮助!保持学习。!如果有帮助就放弃投票...!

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