[英]Async method in Spring Boot
I have a problem with sending email with method annotated as @Async. 我在发送方法为@Async的电子邮件时遇到问题。 Firstly, I am not sure if it is possible to work as I want so I need help with explanation.
首先,我不确定是否可以按照我的意愿进行工作,因此需要我的解释帮助。
Here is what am doing now: 这是现在在做什么:
In main method i have annotation 在主要方法中,我有注释
@EnableAsync(proxyTargetClass = true)
Next I have AsyncConfig class 接下来我有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;
}
}
Of course, its rest application so i have controller, service etc, looks normally, nothing special 当然,它的其余应用程序使我拥有控制器,服务等,看起来正常,没什么特别的
My async method looks like this: 我的异步方法如下所示:
@Async
public void sendEmail() throws InterruptedException {
log.info("Sleep");
Thread.sleep(10000L);
//method code
log.info("Done");
}
I executing this method in another service method: 我在另一个服务方法中执行此方法:
@Override
public boolean sendSystemEmail() {
try {
this.sendEmail();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("pending sendEmail method");
return true;
}
Now what I want archive is to ignore executing sendEmail()
function and execute return true;
现在我想要存档的是忽略执行
sendEmail()
函数并执行return true;
meanwhile function sendEmail()
will be executing in another Thread. 同时,函数
sendEmail()
将在另一个线程中执行。 Of course it doesn't work now as I want. 当然,它现在无法按我的意愿运行。 Unfortunately.
不幸。
Note that I am new into async programming, so I have lack of knowledge in some parts of this programming method. 请注意,我是异步编程的新手,所以我对这种编程方法的某些部分缺乏知识。
Thanks for any help. 谢谢你的帮助。
First – let's go over the rules – @Async has two limitations: 首先-让我们研究一下规则-@Async有两个限制:
it must be applied to public methods only self-invocation – calling the async method from within the same class – won't work 只能将其应用于公共方法,只有自调用–从同一类中调用异步方法–无效
The reasons are simple – the method needs to be public so that it can be proxied. 原因很简单–该方法需要公开,以便可以代理。 And self-invocation doesn't work because it bypasses the proxy and calls the underlying method directly.
而且自调用不起作用,因为它绕过了代理并直接调用了底层方法。
http://www.baeldung.com/spring-async http://www.baeldung.com/spring-async
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.