参考文档:

How can we share data between the different steps of a Job in Spring Batch?

Job Scoped Beans in Spring Batch

https://github.com/spring-projects/spring-batch/issues/1335

有三种方式:

  1. Use StepContext and promote it to JobContext and you have access to it from each step, you must as noted obey limit in size
  2. Create @JobScope bean and add data to that bean, @Autowire it where needed and use it (drawback is that it is in-memory structure and if job fails data is lost, migh cause problems with restartability)
  3. We had larger datasets needed to be processed across steps (read each line in csv and write to DB, read from DB, aggregate and send to API) so we decided to model data in new table in same DB as spring batch meta tables, keep ids in JobContext and access when needed and delete that temporary table when job finishes successfully.

使用 JobContext

通过step_execution 或者 job_execution来在不同step中传递数据。

但是如果数据量大的话,这将不是一种好的方式.因为spring batch默认会通过job repository将 step_executionjob_execution进行持久化.

Use ExecutionContextPromotionListener:

首先在第一个Step中放到StepExecution

public class YourItemWriter implements ItemWriter<Object> {
private StepExecution stepExecution;
public void write(List<? extends Object> items) throws Exception {
// Some Business Logic // put your data into stepexecution context
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("someKey", someObject);
}
@BeforeStep
public void saveStepExecution(Final StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
}

然后使用promotionListener在监听器中将其升级到JobExecution中:

@Bean
public Step step1() {
return stepBuilder
.get("step1")<Company,Company> chunk(10)
.reader(reader()).processor(processor()).writer(writer())
.listener(promotionListener()).build();
} @Bean
public ExecutionContextPromotionListener promotionListener() {
ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener();
listener.setKeys(new String[] {"someKey"});
listener.setStrict(true);
return listener;
}

在第二个Step中使用ExecutionContext获取:

public class RetrievingItemWriter implements ItemWriter<Object> {
private Object someObject;
public void write(List<? extends Object> items) throws Exception {
// ...
}
@BeforeStep
public void retrieveInterstepData(StepExecution stepExecution) {
JobExecution jobExecution = stepExecution.getJobExecution();
ExecutionContext jobContext = jobExecution.getExecutionContext();
this.someObject = jobContext.get("someKey");
}
}

如果你使用的是tasklets的话,可以这样获取:

List<YourObject> yourObjects = (List<YourObject>) chunkContent.getStepContext().getJobExecutionContext().get("someKey");

用自己定义的bean传递数据

创建一个data holder

@Component
@JobScope
public class PublicCompanyHolder { private List<PublicCompanyInfo> publicCompanyList; public List<PublicCompanyInfo> getPublicCompanyList() {
return publicCompanyList;
} public void setPublicCompanyList(List<PublicCompanyInfo> publicCompanyList) {
this.publicCompanyList = publicCompanyList;
} }

在step 1中设置数据:

@Component("pubTasklet")
public class PubTasklet implements Tasklet { @Autowired
private PublicCompanyHolder publicCompanyHolder; public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception { List<PublicCompanyInfo> infoContainer = new ArrayList<PublicCompanyInfo>(); for (int i=0; i < 10; i++) {
PublicCompanyInfo info = new PublicCompanyInfo();
info.setPublicCompanyId("ID-" + i);
info.setPublicCompanyName("Name*" + i);
infoContainer.add(info);
}
publicCompanyHolder.setPublicCompanyList(infoContainer); return RepeatStatus.FINISHED;
} }

在step2中取数据:

@Component("pubTasklet2")
public class PubTasklet2 implements Tasklet {
@Autowired
private PublicCompanyHolder publicCompanyHolder; public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
System.out.println("received holder:" + publicCompanyHolder.getPublicCompanyList()); return RepeatStatus.FINISHED;
} }

job配置

  • define.xml
  <job id="pubJob" restartable="true">
<step id="step1" next="step2">
<tasklet ref="pubTasklet" />
</step>
<step id="step2" next="step1"> // if you do not want to loop, remove next
<tasklet ref="pubTasklet2" />
</step>
<listeners>
<listener ref="pubListener" />
</listeners>
</job>
  • Job Config
public Job build(Step step1, Step step2) {
return jobBuilderFactory.get("jobName")
.incrementer(new RunIdIncrementer())
.start(step1)
.next(step2)
.build();
}
public Step step1() {
return stepBuilderFactory.get("step1Name")
.tasklet(new PubTasklet())
.build();
} public Step step2() {
return stepBuilderFactory.get("step2Name")
.tasklet(new PubTasklet2())
.build();
}

Spring Batch : 在不同steps间传递数据的更多相关文章

  1. 小菜学习Winform(五)窗体间传递数据

    前言 做项目的时候,winfrom因为没有B/S的缓存机制,窗体间传递数据没有B/S页面传递数据那么方便,今天我们就说下winfrom中窗体传值的几种方式. 共有字段传递 共有字段传递实现起来很方便, ...

  2. C#中使用SendMessage在进程间传递数据的实例

    原文:C#中使用SendMessage在进程间传递数据的实例 1 新建解决方案SendMessageExample 在解决方案下面新建三个项目:CopyDataStruct,Receiver和Send ...

  3. StoryBoard学习(5):使用segue页面间传递数据

    StoryBoard学习(5):使用segue页面间传递数据 函数: - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sen ...

  4. 使用Bundle在Activity间传递数据

    使用Bundle在Activity间传递数据 源Activity public class SourceActivty extends Activity { private Intent intent ...

  5. WinForm 窗体间传递数据

    前言 做项目的时候,winfrom因为没有B/S的缓存机制,窗体间传递数据没有B/S页面传递数据那么方便,今天我们就说下winfrom中窗体传值的几种方式. 共有字段传递 共有字段传递实现起来很方便, ...

  6. 在微信小程序页面间传递数据总结

    在微信小程序页面间传递数据 原文链接:https://www.jianshu.com/p/dae1bac5fc75 在开发微信小程序过程之中,遇到这么一些需要在微信小程序页面之间进行数据的传递的情况, ...

  7. iPhone应用程序间传递数据

    前一篇简单的介绍了iPhone应用程序间通信,主要是通过在被调用应用的Info.plist中加入URL方案,在应用中通过openUrl来实现程序的调用.而应用程序间的数据传递则可以更具url来实现,例 ...

  8. Android程序中Acticity间传递数据

    在Android开发过程中,在不同的Acitivity之间传递数据的情况是非常常见的.我花费了一点时间来总结Acitivity之间的数据传递,记录下来. 1.简单传递键值对 这种传递方式非常简单,只需 ...

  9. Android学习手记(3) Activity间传递数据

    1. 简单数据传递 建立两个Activity,名称分别为MainActivity和TheAty,在MainActivity中新建一个Button,id为btnStartAty.在TheAty中新建一个 ...

随机推荐

  1. druid连接泄露故障分析

    1.问题的如何发生的 1.1.应用功能介绍 系统是一个双数据源双写单独的服务.(两个数据源是不同的存储,所以无法使用主从复制的模式,是一个切换存储介质的过渡态). 历史代码有个更新逻辑update x ...

  2. 【JAVA】编程(2)---时间管理

    作业要求: 定义一个名为 MyTime 的类,其中私有属性包括天数,时,分,秒:定义一个可以初始化时,分,秒的构造方法,并对初始化数值加以限定,以防出现bug:定义一个方法,可以把第几天,时,分,秒打 ...

  3. QuantumTunnel:v1.0.0 正式版本发布

    经过一段时间运行,代码已经稳定是时候发布正式版本了! v1.0.0 正式版本发布 对核心能力的简要说明: 支持协议路由和端口路由:QuantumTunnel:端口路由 vs 协议路由 基于Netty实 ...

  4. java开发环境搭建,配置

    java开发环境搭建 下载jdk8的地址 是oracle的 安装JDK 下载电脑对应的版本 双击安装JDK 记住安装路径 配置环境变量 我的电脑/此电脑 右键属性 高级设置 环境变量 点击新建 变量名 ...

  5. 路径前面加与不加"/"的区别

    加"/"是绝对路径, 不加"/"是相对路径.假设你的这个html文件的路径是www.example.com/path/to/html/a.html,那么src= ...

  6. Java是用JDBC连接MySQL数据库

    首先要下载Connector/J地址:http://www.mysql.com/downloads/connector/j/ 这是MySQL官方提供的连接方式: 解压后得到jar库文件,需要在工程中导 ...

  7. [loj3256]火灾

    将问题差分,即求$\sum_{i=1}^{r}S_{i}(t)-\sum_{i=1}^{l-1}S_{i}(t)$,由于两者类似,不妨考虑前者 构造矩阵$A_{i,j}=S_{j}(i)-S_{j}( ...

  8. [loj2978]杜老师

    假设所有素数从小到大依次为$p_{1},p_{2},...,p_{k}$,我们将$x$转换为一个$k$位的二进制数,其中从低到高第$i$位为1当且仅当其$p_{i}$的幂次为奇数 不难发现以下两个性质 ...

  9. [loj519]数学上来先打表

    建立操作树,即1和3操作时i-1向i连边,2操作中k向i连边,然后dfs一遍 那么当我们走到一个节点,就执行该操作(修改也是操作),退出后取消该操作即可 于是相当于要维护一个东西,支持:1.加边:2. ...

  10. Codeforces 739C - Alyona and towers(线段树)

    Codeforces 题目传送门 & 洛谷题目传送门 可能有人会问我为什么为这道 *2500 的 D1C 写题解,我觉得大概是想要在写题解数量上 dd ycx 吧,因为 ycx 到目前为止写了 ...