gpt4 book ai didi

java - Spring @Async 注解方法在调用自身时阻塞

转载 作者:行者123 更新时间:2023-11-30 09:10:37 25 4
gpt4 key购买 nike

在我的软件中,我使用 @AsyncTomcat 启动时从后台的 Bean 调用特定方法,这有效正如预期的那样。

但是,在某些定义的情况下,该方法所做的事情会失败,然后该方法 myUtil.connect() 会调用自身重试。

基本代码如下所示。

bean 定义:

import org.springframework.context.annotation.Bean;
import package.MyService;

@Bean(initMethod = "init", destroyMethod = "destroy")
MyService myService() {
MyService bean = new MyService();
return bean;
}

还有 MyService bean:

import javax.inject.Inject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class MyService {

@Inject
private MyUtil myUtil;

@Async
public void init() {
myUtil.connect();
}
}

我已经尝试用 @Async 注释方法 connect() 相信,因为它调用自己,@Async 会让它运行也在后台,但没有成功。

有没有办法确保对 connect() 的后续调用“保持”在后台?

编辑:

connect() 做成一个真正起作用的函数的包装器会起作用吗?这样 connect() 只会被调用一次,而被包装的函数会在失败时调用自身。

最佳答案

我的要求的工作解决方案是这样的:

首先,我必须将 @EnableAsync 添加到我的根上下文配置类(这是创建 MyService bean 的配置类)。

然后我将 @Async 注释从 MyService 移到了 MyUtils 类。

我的服务类:

import javax.inject.Inject;
import org.springframework.stereotype.Component;

@Component
public class MyService {

@Inject
private MyUtil myUtil;


public void init() {
myUtil.connect();
}
}

MyUtil 类:

@Component
public class MyUtil {

@Async
public void connect() {}

}

文档位于 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-async给出了必要的提示:

To asynchonously initialize Spring beans you currently have to use a separate initializing Spring bean that invokes the @Async annotated method on the target then.

关于java - Spring @Async 注解方法在调用自身时阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22465351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com