Spring 3:如何从TaskExecutor调用@Async注释方法 [英] Spring 3: How to call @Async annotated methods from the TaskExecutor

查看:583
本文介绍了Spring 3:如何从TaskExecutor调用@Async注释方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring的异步任务执行新手,所以如果这听起来像个愚蠢的问题,请原谅我。

I'm new to asynchronous task execution in Spring, so please forgive me if this sounds like a silly question.

我读到@Async注释是从方法级别的Spring 3.x向前调用该方法将异步发生。
我还读到我们可以在spring配置文件中配置ThreadPoolTask​​Executor。

I read that @Async annotation is introduced from Spring 3.x onward at method level to invocation of that method will occur asynchronously. I also read that we can configure the ThreadPoolTaskExecutor in the spring config file.

我无法理解的是如何调用@Async来自tak执行者的注释方法让我们假设 - AsyncTaskExecutor

What I'm not able to understand is that how to call a @Async annotated method from a tak executor lets suppose - AsyncTaskExecutor

之前我们曾经做过类似的事情:

Earlier we used to do something like in a class:

@Autowired protected AsyncTaskExecutor executor;

然后

executor.submit(<Some Runnable or Callable task>)

我是无法理解@Async注释方法和TaskExecutor之间的关系。

I'm not able to understand the relationship between @Async annotated methods and TaskExecutor.

我尝试在互联网上搜索很多东西,但却无法得到任何相关信息。

I tried searching a lot over the internet but could not get anything on this.

有人可以提供相同的例子。

Can somebody provide an example for the same.

推荐答案

以下是<$的示例c $ c> @Async 使用:

@Async
void doSomething() {
    // this will be executed asynchronously
}

现在调用该方法另一个类,它将异步运行。如果你想要一个返回值,请使用 Future

Now call that method from another class and it will run asynchronously. If you want a return value use a Future

@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
}

@Async TaskExecutor 之间的关系是 @Async 在幕后使用 TaskExecutor 。来自文档:

The relationship between @Async and TaskExecutor is that @Async uses a TaskExecutor behind the scenes. From the docs:


默认情况下,在方法上指定@Async时,将使用的执行程序是提供给'注释的执行程序如上所述的驱动元素。但是,当需要指示在执行给定方法时应该使用除默认值之外的执行程序时,可以使用@Async批注的value属性。

By default when specifying @Async on a method, the executor that will be used is the one supplied to the 'annotation-driven' element as described above. However, the value attribute of the @Async annotation can be used when needing to indicate that an executor other than the default should be used when executing a given method.

因此,要设置默认执行程序,请将其添加到spring config

So to set up a default executor, add this to your spring config

<task:annotation-driven executor="myExecutor" />

或者使用特定执行人一次性尝试

Or to use a particular executor for a single use try

@Async("otherExecutor")

请参阅 http:// docs .spring.io / spring / docs / 3.2.x / spring-framework-reference / html / scheduling.html#scheduling-annotation-support-async

这篇关于Spring 3:如何从TaskExecutor调用@Async注释方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆