在哪里应该放置@EnableAsync注解?

20

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

我的方法是这样的。

//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注释放在哪里?这与计划无关,当用户单击保存按钮时发生。该应用程序使用flex spring blazeDS,没有由我自己编写的控制器。

我已经在我的代码中使用了@Async注释来调用Mail类中的以下两个方法。

@Async
sendEmailQuote(listOfData){}

@Async
sendEmailWorkflowTaskAssignment(listOfData){}

你能帮我找一下在哪里应该放置@EnableAsync吗?

我参考了这个示例

2个回答

23

EnableAsync 用于配置和启用Spring的异步方法执行功能,不应放在您的 ServiceComponent 类上,而应该放在您的 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类之上,该类使用AsyncExecutor配置扩展了 AsyncConfigurerSupport :
@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;
}
}

1
如果您按照 https://spring.io/guides/gs/async-method/ 一步一步地操作,它会起作用的。正确的配置应该是:1. 在您的 MyService 类上方放置 @Service; 2. 在 MyService 中的方法上方放置 @Async; 3. @EnableAsync@SpringBootApplication 都要放在您的 Application 类上方。或者您能否把您已经尝试过的所有代码都发布一下? - shizhz
1
如果我想在Spring项目中使用它,而不是Spring Boot项目呢? - keith5140

18

请确保@Async方法不会被同一类调用。使用代理进行自我调用将无法实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接