Spring @Async被忽略了 [英] Spring @Async ignored
问题描述
我在Spring中异步调用方法时遇到麻烦,因为调用程序是一个从外部系统接收通知的嵌入式库。代码如下所示:
I am having troubles invoking a method asynchronously in Spring, when the invoker is an embedded library receiving notifications from an external system. The code looks as below:
@Service
public class DefaultNotificationProcessor implements NotificationProcessor {
private NotificationClient client;
@Override
public void process(Notification notification) {
processAsync(notification);
}
@PostConstruct
public void startClient() {
client = new NotificationClient(this, clientPort);
client.start();
}
@PreDestroy
public void stopClient() {
client.stop();
}
@Async
private void processAsync(Notification notification) {
// Heavy processing
}
}
NotificationClient
内部有一个线程,它接收来自另一个人的通知系统。它在其构造函数中接受 NotificationProcessor
,它基本上是将对通知进行实际处理的对象。
The NotificationClient
internally has a thread in which it receives notifications from another system. It accepts a NotificationProcessor
in its constructor which is basically the object that will do the actual processing of notifications.
In上面的代码,我已经将Spring bean作为处理器,并尝试使用 @Async
注释异步处理通知。但是,似乎通知在与 NotificationClient
使用的线程相同的线程中处理。实际上, @Async
将被忽略。
In the above code, I have given the Spring bean as the processor and attempted to process the notification asynchronously by using @Async
annotation. However, it appears the notification is processed in the same thread as the one used by NotificationClient
. Effectively, @Async
is ignored.
我在这里缺少什么?
推荐答案
@Async
(以及当通过
和其他类似的注释将无法工作(当这个
调用该方法时,@ transnsal @Async时
@Async
(as well as @Transactional
and other similar annotations) will not work when the method is invoked via this
(on when @Async
is used for private methods*), as long as you do not use real AspectJ compiletime or runtime weaving.
*私有方法是:当方法是私有的时,必须通过调用此
- 所以这就是结果然后原因
*the private method thing is: when the method is private, then it must been invoked via this
- so this is more the consequence then the cause
所以改变你的代码:
@Service
public class DefaultNotificationProcessor implements NotificationProcessor {
@Resource
private DefaultNotificationProcessor selfReference;
@Override
public void process(Notification notification) {
selfReference.processAsync(notification);
}
//the method must not been private
//the method must been invoked via a bean reference
@Async
void processAsync(Notification notification) {
// Heavy processing
}
}
另见以下答案: Spring @Transactional属性是否适用于私有方法? - 这是同样的问题
See also the answers for: Does Spring @Transactional attribute work on a private method? -- this is the same problem
这篇关于Spring @Async被忽略了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!