spring batch从文件中获取数据并传递给过程
问题描述:
对于Spring批处理项目,我需要从文件中获取日期,然后我需要将此日期传递给过程,然后运行该过程。spring batch从文件中获取数据并传递给过程
然后过程的结果必须写入一个csv文件。
我尝试使用监听器,但无法做到这一点。
任何人都可以请告诉如何实现这一点,或者如果可能的话,你可以在github中分享任何示例代码。
答
首先,您需要从文件中获取日期并将其存储在JobExecutionContext
中。一个最简单的解决方案是创建一个自定义Tasklet
阅读文本文件,并通过StepExecutionListener
在上下文结果String
存储该微进程需要一个file
参数,并将结果存储串钥匙file.date
:
public class CustomTasklet implements Tasklet, StepExecutionListener {
private String date;
private String file;
@Override
public void beforeStep(StepExecution stepExecution) {}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
stepExecution.getJobExecution().getExecutionContext().put("file.date", date);
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// Read from file using FileUtils (Apache)
date = FileUtils.readFileToString(file);
}
public void setFile(String file) {
this.file = file;
}
}
使用这种方式:
<batch:step>
<batch:tasklet>
<bean class="xx.xx.xx.CustomTasklet">
<property name="file" value="${file.path}"></property>
</bean>
</batch:tasklet>
</batch:step>
然后你将使用Chunk
与后期绑定检索先前存储的值(即,使用#{jobExecutionContext['file.date']}
)。
读者将是一个StoredProcedureItemReader
:
<bean class="org.springframework.batch.item.database.StoredProcedureItemReader">
<property name="dataSource" ref="dataSource" />
<property name="procedureName" value="${procedureName}" />
<property name="fetchSize" value="50" />
<property name="parameters">
<list>
<bean class="org.springframework.jdbc.core.SqlParameter">
<constructor-arg index="0" value="#{jobExecutionContext['file.date']}" />
</bean>
</list>
</property>
<property name="rowMapper" ref="rowMapper" />
<property name="preparedStatementSetter" ref="preparedStatementSetter" />
</bean>
笔者将是一个FlatFileItemWriter
:
<bean class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<property name="resource" value="${file.dest.path}" />
<property name="lineAggregator" ref="lineAggregator" />
</bean>
这听起来像一个典型的读 - >程序 - >写。阅读Spring Batch文档并尝试提供自己的东西,这就是Spring Batch的用途,它的文档写得很好。 – Tunaki