2017-02-13 79 views
0

在我的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(); 
} 

}

+0

这不起作用,因为它首先是一个内部方法调用(由于AOP的代理不起作用)。其次,你不能将'@ Async'应用于'static'方法。所以它根本无法工作。 “@ Scheduled”是为此而发明的,不要试图再次创建自己的。如果你有大量的数据,你可能需要考虑将其与Spring Batch结合起来。 –

回答

0

你可能会从引进Spring batch到你的应用程序中受益。目前,您对批次中发生的情况没有太多的控制,例如在作业失败时会发生什么情况,或者应该同时处理多少个项目,或者应该在多线程环境中运行。

随着Spring Batch的,你可以创建一个ItemReaderWagerBoardMarksRepo读取,一个ItemProcessor你的实体转化为你的输出和内StoreDbEntRepo存储项目的ItemWriter。解释这一切将会过于宽泛,但您可以阅读他们的reference guide以开始使用。

要每30分钟安排一次任务,您可以使用@Scheduled annotation。只需配置fixedDelay并使其运行批处理作业。或者,您也可以使用cron语法指定延迟。

一个例子:

@Scheduled(fixedDelay = 1800000) // 1000 millis * 1800 seconds = 30 minutes 
public void doBatch() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException { 
    jobLauncher.run(batchJob, new JobParametersBuilder().toJobParameters()); 
} 
1

计划是这样的操作进行,见下文

@Component 
public class ScheduledTasks { 
    @Scheduled(cron = "0 0,30 * * * * ?") 
    public void update() { 
     // get data from loadRepo. 
     // save data to storeRepo 
    } 
} 

代码不要忘记在你的启动类使用@EnableScheduling

@SpringBootApplication 
@EnableScheduling 
public class Application { 

    public static void main(String[] args) throws Exception { 
     SpringApplication.run(Application.class); 
    } 
} 

Scheduling Tasks春季文档了解更多详情。

相关问题