[英]Async method in Spring Boot
我在发送方法为@Async的电子邮件时遇到问题。 首先,我不确定是否可以按照我的意愿进行工作,因此需要我的解释帮助。
这是现在在做什么:
在主要方法中,我有注释
@EnableAsync(proxyTargetClass = true)
接下来我有AsyncConfig类
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import java.util.concurrent.Executor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class AsyncConfig extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("email-");
executor.initialize();
return executor;
}
}
当然,它的其余应用程序使我拥有控制器,服务等,看起来正常,没什么特别的
我的异步方法如下所示:
@Async
public void sendEmail() throws InterruptedException {
log.info("Sleep");
Thread.sleep(10000L);
//method code
log.info("Done");
}
我在另一个服务方法中执行此方法:
@Override
public boolean sendSystemEmail() {
try {
this.sendEmail();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("pending sendEmail method");
return true;
}
现在我想要存档的是忽略执行sendEmail()
函数并执行return true;
同时,函数sendEmail()
将在另一个线程中执行。 当然,它现在无法按我的意愿运行。 不幸。
请注意,我是异步编程的新手,所以我对这种编程方法的某些部分缺乏知识。
谢谢你的帮助。
首先-让我们研究一下规则-@Async有两个限制:
只能将其应用于公共方法,只有自调用–从同一类中调用异步方法–无效
原因很简单–该方法需要公开,以便可以代理。 而且自调用不起作用,因为它绕过了代理并直接调用了底层方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.