我们在开发项目的时候,当在执行主程序的时候,需要一些程序异步执行,在spring中通常使用@Async这种注解方式。但是很多时候,我虽然使用了@Async这种异步方式,但是有的时候并不能真正的异步执行。是什么原因导致的呢。我们今天就说下。
首先,你要正确的使用@Async这个,必须要又如下两步:
1:在springBoot的启动类上添加
@EnableAsync
2:在对应的方法上添加
@Async
这样你启动的时候就可以用了。既然如此简单,还又什么说多呢。
那就是你虽然这样注解了。但是没有真正的异步执行。什么原因导致的呢。
看下官网是如何解释使用@Async
First, let's go over the rules. @Async has two limitations:
- 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.
上面是官网的说法。第二个就是调用自己类上的异步方法是不起作用的。就是这种使用方式绕过了代理而直接调用了方法,所以肯定是同步的了。从这里,我们也知道了另外一个知识点,就是@Async注解其实是通过代理的方式来实现异步调用的。