在我的Spring Boot应用程序中,我试图在后台执行一些任务。Java Spring Boot - 用于在后台运行的异步数据库操作的CommandLineRunner
从一个数据库获取数据,并将其存储在另一个数据库中,每隔30分钟保存一次。
使用@Async创建一个处理此问题的CommandLineRunner类会是正确的吗?
@Component
public class UpdateDB implements CommandLineRunner {
@Autowired
private WagerBoardMarksRepo loadRepo;
@Autowired
private StoreDbEntRepo storeRepo;
@Async
private static void update() {
while (true) {
// get data from loadRepo.
// save data to storeRepo
try {
Thread.sleep("sleep for 30min"); //
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void run(String... args) throws Exception {
update();
}
}
这不起作用,因为它首先是一个内部方法调用(由于AOP的代理不起作用)。其次,你不能将'@ Async'应用于'static'方法。所以它根本无法工作。 “@ Scheduled”是为此而发明的,不要试图再次创建自己的。如果你有大量的数据,你可能需要考虑将其与Spring Batch结合起来。 –