我需要在将数据保存到数据库时以异步方式发送电子邮件。
我的方法是这样的。
//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。没有自己写的controller。
我在我的代码中为以下 2 个方法使用了 @Async 注释。那些在类调用邮件中。
@Async
sendEmailQuote(listOfData){}
@Async
sendEmailWorkflowTaskAssignment(listOfData){}
你能帮我找到我应该把 @EnableAsync 放在哪里吗?
最佳答案
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;
}
}
请引用it's java doc了解更多详情。
对于您遵循的教程,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;
}
}
关于java - 我应该在哪里放置@EnableAsync 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43244618/