【问题标题】:@Async in Spring doesn't work in Service class?Spring中的@Async在Service类中不起作用?
【发布时间】:2017-02-23 20:19:43
【问题描述】:

独立 Spring Boot 应用程序中@Service 注释类中的@Async 方法不会异步运行。我做错了什么?

当我直接从主类(@SpringBootApplication 注释)运行相同的方法时,它可以工作。示例:

主类

@SpringBootApplication
@EnableAsync
public class Application implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // here when I call downloadAnSave() it runs asynchronously...
        // but when I call downloadAnSave() via downloadAllImages() it does not run asynchronously...
    }

}

和我的服务类(这里异步行为不起作用):

@EnableAsync
@Service
public class ImageProcessorService implements IIMageProcessorService {

    public void downloadAllImages(Run lastRun) {
        // this method calls downloadAnSave() in loop and should run asynchronously....
    }

    @Async
    @Override
    public boolean downloadAnSave(String productId, String imageUrl) {
        //
    }

}

【问题讨论】:

标签: java asynchronous spring-boot


【解决方案1】:

在同一个类中调用异步方法会触发原始方法,而不是被拦截的方法。 您需要使用 async 方法创建另一个服务,并从您的服务中调用它。

Spring 为您使用公共注解创建的每个服务和组件创建一个代理。只有那些代理包含由方法注释(例如 Async)定义的所需行为。因此,不是通过代理而是通过原始裸类调用这些方法不会触发这些行为。

【讨论】:

  • 谢谢,我试试。为了澄清和我的信息,请您解释一下“会触发原始方法而不是拦截的方法”是什么意思?谢谢。
  • 您也可以自行注入,它会起作用,但我认为不建议这样做,因为它通常会违反单一责任原则
  • 你能解释一下为什么自注入会破坏“单一职责原则”吗?
  • 非常感谢。在其他服务中完美运行
【解决方案2】:

解决方法是:

@EnableAsync
@Service("ip-service")
public class ImageProcessorService implements IIMageProcessorService {
    
    @Autowired
    @Qualifier("ip-service")
    ImageProcessorService ipService;

    public void downloadAllImages(Run lastRun) {
        // this method calls downloadAnSave() in loop and should run asynchronously....
        ipService.downloadAnSave(productId, imageUrl);
    }

    @Async
    @Override
    public boolean downloadAnSave(String productId, String imageUrl) {
        //
    }
}

使用这种方法,您调用的是代理方法,而不是类实例。 相同的方法可以用于使用代理的其他工具,例如@Transactional 等

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 2018-12-30
    • 2012-01-31
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多