gpt4 book ai didi

java - 服务中的 Spring @Async 方法

转载 作者:IT老高 更新时间:2023-10-28 13:58:25 25 4
gpt4 key购买 nike

我有一个带有 sync 方法的服务 bean,它调用内部 async 方法:

@Service
public class MyService {

public worker() {
asyncJob();
}

@Async
void asyncJob() {
...
}

}

问题在于 asyncJob 并没有真正以 async 方式调用。我发现这不起作用,因为内部调用跳过了 AOP 代理

所以我尝试 self 引用 bean:

@Service
public class MyService {

MyService mySelf;

@Autowired
ApplicationContext cnt;

@PostConstruct
public void init() {
mySelf=(MyService)cnt.getBean("myService");
}


public void worker() {
mySelf.asyncJob();
}

@Async
void asyncJob() {
...
}

}

失败了。再次没有 async 调用。

所以我尝试将它分成两个 bean :

@Service
public class MyService {

@Autowired
MyAsyncService myAsyncService;

public void worker() {
myAsyncService.asyncJob();
}
}

@Service
public class MyAsyncService {

@Async
void asyncJob() {
...
}

}

再次失败


唯一可行的方法是从 Controller Bean 调用它:

@Controller
public class MyController {

@Autowired
MyAsyncService myAsyncService;

@RequestMapping("/test")
public void worker() {
myAsyncService.asyncJob();
}

}

@Service
public class MyAsyncService {

@Async
public void asyncJob() {
...
}

}

但在这种情况下,它是一项服务工作。为什么我不能从服务调用它?

最佳答案

找到了一种非常好的方法来解决这个问题(使用 java8),在你有很多不同的东西想要同步和异步的情况下。不要为每个“同步”服务创建单独的 XXXAsync 服务,而是创建一个通用的异步服务包装器:

@Service
public class AsyncService {

@Async
public void run(final Runnable runnable) {
runnable.run();
}
}

然后这样使用它:

@Service
public class MyService {

@Autowired
private AsyncService asyncService;


public void refreshAsync() {
asyncService.run(this::refresh);
}


public void refresh() {
// my business logic
}


public void refreshWithParamsAsync(String param1, Integer param2) {
asyncService.run(() -> this.refreshWithParams(param1, param2));
}


public void refreshWithParams(String param1, Integer param2) {
// my business logic with parameters
}

}

关于java - 服务中的 Spring @Async 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24798695/

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