异步不适用于控制器的抽象超类方法 [英] Async not working on controller's abstract super class method

查看:26
本文介绍了异步不适用于控制器的抽象超类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Rest 控制器扩展的 BaseRestController 类.它有一个我想异步运行的方法.

I have a BaseRestController class that Rest controllers extend. It has a method that I want to run asynchronously.

public abstract class BaseRestController {
    ...

    @Async("someThreadPoolTaskExecutor")
    public void someAsyncTask() {
        ...
    }

}

@RestController
public class MyRestController extends BaseRestController {
    ...

    @GetMapping("/some/path")
    public SomeEntity getSomething() {
        ...
        this.someAsyncTask();
    }        
}

我使用注释启用了 Async,实现了一个获取 someThreadPoolTask​​Executor TaskExecutor 和所有的方法.如果我将 @Async("someThreadPoolTask​​Executor") 放在服务的(用 @Service 注释的类)方法上,它可以工作,但如果我使用 someAsyncTask()BaseRestController 中的代码不会异步运行.用 @Component 装饰类也不起作用.

I have enabled Async using annotation, implemented a method that gets someThreadPoolTaskExecutor TaskExecutor and all. If I put @Async("someThreadPoolTaskExecutor") on a Service's (class annotated with @Service) method, it works but if I do so with someAsyncTask() in BaseRestController the code won't run asynchronously. Decorating the class with @Component didn't work either.

Spring 异步指南也没有帮助.在它的演示中,它还演示了 Async 与服务类.

Spring guide on Async didn't help either. In it's demo, it also demonstrates Async with service class.

虽然在这个过程中,我意识到我想要实现的行为最好委托给服务类,但我很好奇为什么上述方法不起作用.

While, in the process, I realized that the behavior I wanted to implement was better off delegated to a service class, I am curious as to understand why the above won't work.

我正在使用 Spring Boot 的 2.1.0.RELEASE.

I'm using 2.1.0.RELEASE of Spring Boot.

推荐答案

@Async 有几条规则,您正在执行无法正常工作的自调用 这里

There are couple of rules for @Async, you are doing the self-invocation which won't work here

  • 它只能应用于公共方法
  • 自调用——从同一个类中调用异步方法——不起作用

原因很简单——该方法需要是公开的,以便它可以被代理.而且自调用不起作用,因为它绕过了代理,直接调用了底层方法.

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.

这篇关于异步不适用于控制器的抽象超类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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