java - 如何使 Aysnc 注释在 Spring Boot 中工作?
问题描述
我创建了一个带有预定 ( @Scheduled
) 任务的简单 Spring Boot 应用程序。在那个计划任务中,我想用 调用 async 函数@Async
,但我可以看到它仍然在调度线程上运行,而无需切换到另一个线程。我也尝试自定义执行器,但没有运气。这里有一些代码。我也已经在主类中启用了异步
public class scheduledService {
@Scheduled(fixedRateString = "${config.scheduleInterval}")
public void pollDataWithFixSchedule() {
AsyncService service = new AsyncService();
service.asyncCall();
service.asyncCall();
service.asyncCall();
asyncCall();
}
}
public class AsyncService {
@Async()
public void asyncCall(){
System.out.printly("Current thread -- {}",Thread.currentThread().getName()))
Thread.sleep(10000);
}
}
@Bean(name = "MyThreadPoolExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("MyThreadPoolExecutor-");
executor.initialize();
return executor;
}
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class ScheduledApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(ScheduledApplication.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
}
解决方案
根据Baeldung:
@Async 有两个限制:
- 它必须仅应用于公共方法
- 自调用——从同一个类中调用异步方法——不起作用
原因很简单——方法需要公开才能被代理。而自调用也不起作用,因为它绕过了代理,直接调用了底层方法。所以你可以把你的异步方法放在一个服务中并从那里使用它
推荐阅读
- react-native - navigation.navigate 不是函数
- java - 调试 apk 没有问题,但在发布 apk 时在 GoogleSignInApi 中发现“signInResult:failed code=12500”异常
- elasticsearch - 如何将地理数据添加到弹性搜索查询(elasticsearch 6.4)?
- c++ - 与 .exe 文件相关的 SFML 安装问题
- yii2 - yii2 全局行为检查模块中的语言
- java - 运行 hadoop 流和 mapreduce 作业:PipeMapRed.waitOutputThreads():子进程失败,代码为 127
- android - 为什么 cordova-plugin-file 是一个这么慢的作家?
- command-line - 如何使用“less”命令读取一行长文本
- java - ORM如何映射到接口?
- android - 键盘没有隐藏