簡體   English   中英

spring 批處理使用 spring 啟動:從配置或命令行讀取 arguments 並在作業中使用它們

[英]spring batch using spring boot: Read arguments from config or command line and use them in job

我對 spring 技術很陌生。 我正在嘗試使用 spring 批處理和 spring 啟動構建類似 ETL 的應用程序。

能夠運行基本作業(讀取->處理->寫入)。 現在,我想從配置文件(稍后)或命令行(現在可以使用它)中讀取 arguments(如日期、文件名、類型等)並在我的工作中使用它們。

入口點:

// Imports
@SpringBootApplication
@EnableBatchProcessing
public class EtlSpringBatchApplication {

    public static void main(String[] args) {
        SpringApplication.run(EtlSpringBatchApplication.class, args);
    }

}

我的批處理配置

// BatchConfig.java
// Imports
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    public MyDao myDao;

    @Bean
    public Job job() {
        return jobBuilderFactory
                .get("job")
                .incrementer(new RunIdIncrementer())
                .listener(new Listener(myDao))
                .flow(step1())
                .end()
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1").<myModel, myModel>chunk(1000)
                .reader(Reader.reader("my_file_20200520.txt"))
                .processor(new Processor())
                .writer(new Writer(myDao))
                .build();
    }

我有基本的步驟步驟。

Reader.java 有讀取平面文件的方法。

public static FlatFileItemReader<MyModel> reader(String path) {......}

Processor.java 已定義處理方法。 我添加了一個@BeforeStep 從數據庫中獲取處理所需的一些詳細信息。

public class Processor implements ItemProcessor<MyModel, MyModel> {

    private static final Logger log = LoggerFactory.getLogger(Processor.class);
    private Long id = null;

    @BeforeStep
    public void getId(StepExecution stepExecution) {
        this.id = stepExecution.getJobExecution().getExecutionContext().getLong("Id");
    }

    @Override
    public MyModel process(MyModel myModel) throws Exception {
    }
}

Writer.java 正在實現 ItemWriter 並編寫代碼。

Listener.java 擴展了 JobExecutionListenerSupport 並覆蓋了 afterJob 和 beforeJob 方法。 基本上嘗試在 beforeJob 中使用 executioncontext。

@Override
public void beforeJob(JobExecution jobExecution) {
    log.info("Getting the id..");
    this.id = myDao.getLatestId();
    log.info("id retrieved is: " + this.id);
    jobExecution.getExecutionContext().putLong("Id", this.id);
}

現在,我正在尋找的是:

  • 讀者應該從作業 arguments 中獲取文件名。 即在運行作業時,我應該能夠提供一些 arguments,其中之一是文件路徑。
  • 稍后一些方法(如獲取 id 等)需要更多的變量,這些變量可以作為 arguments 傳遞給作業,即 run_date、類型等。

簡而言之,我正在尋找一種方法,

  • 將作業 arguments 傳遞給我的應用程序(運行日期、類型、文件路徑等)
  • 在閱讀器和其他地方使用它們(聽眾,作家)

有人可以提供我應該在我的 BatchConfig.java 和其他地方做些什么來讀取作業參數(從命令行或配置文件,以容易的為准)嗎?

您可以從閱讀器內的配置文件或 spring 批處理執行上下文中的其他類中讀取作業參數集的值。 下面是一個片段供參考,

application.yml 文件可以有以下配置,

batch.configs.filePath: c:\test

您可以在啟動作業時將從配置中讀取的 filePath 添加到作業參數中。 class 的片段,

// Job and Job Launcher related autowires..

@Value("${batch.configs.filePath}")
private String filePath;

// inside a method block,
JobParameters jobParameters = new JobParametersBuilder().addLong("JobID", System.currentTimeMillis())
            .addString("filePath", filePath).toJobParameters();

try {
    jobLauncher.run(batchJob, jobParameters);
} catch (Exception e) {
    logger.error("Exception while running a batch job {}", e.getMessage());
}

訪問作業參數的一種方法是對您的閱讀器 Class 實施 StepExecutionListener,以利用其覆蓋的方法 beforeStep 和 afterStep。 也可以對其他類執行類似的實現,

public class Reader implements ItemReader<String>, StepExecutionListener {

private String filePath;

@Override
public void beforeStep(StepExecution stepExecution) {

    try {
        filePath = (String) stepExecution.getJobExecution().getExecutionContext()
                .get("filePath");
    } catch (Exception e) {
        logger.error("Exception while performing read {}", e);
    }
}


@Override
public String read() throws Exception {
    // filePath value read from the job execution can be used inside read use case impl

}

@Override
public ExitStatus afterStep(StepExecution stepExecution) {
    return ExitStatus.COMPLETED;
}

}

Spring Batch 和 Spring 引導參考文檔都顯示了如何將參數傳遞給作業:

此外,Spring 批處理文檔詳細解釋了如何在批處理組件(如讀取器、寫入器等)中使用這些參數並附有代碼示例:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM