gpt4 book ai didi

Spring 批处理 : pass data between reader and writer

转载 作者:行者123 更新时间:2023-12-02 09:35:02 24 4
gpt4 key购买 nike

我想获取我在步骤的读取器中设置的写入器中的数据。我通过 http://docs.spring.io/spring-batch/trunk/reference/html/patterns.html#passingDataToFutureSteps 了解 ExecutionContexts(步骤和作业)和 ExecutionContextPromotionListener

问题是在 Writer 中我检索的是“npag”的空值。

ItemWriter 上的行:

LOG.info("INSIDE WRITE, NPAG: " + nPag);

我一直在做一些解决方法,但没有运气,正在寻找其他similar questions的答案...有什么帮助吗?谢谢!

这是我的代码:

阅读器

@Component
public class LCItemReader implements ItemReader<String> {

private StepExecution stepExecution;

private int nPag = 1;

@Override
public String read() throws CustomItemReaderException {

ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("npag", nPag);
nPag++;
return "content";
}

@BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
}

作家

@Component
@StepScope
public class LCItemWriter implements ItemWriter<String> {

private String nPag;

@Override
public void write(List<? extends String> continguts) throws Exception {
try {
LOG.info("INSIDE WRITE, NPAG: " + nPag);
} catch (Throwable ex) {
LOG.error("Error: " + ex.getMessage());
}
}

@BeforeStep
public void retrieveInterstepData(StepExecution stepExecution) {
JobExecution jobExecution = stepExecution.getJobExecution();
ExecutionContext jobContext = jobExecution.getExecutionContext();
this.nPag = jobContext.get("npag").toString();
}
}

作业/步骤批量配置

@Bean
public Job lCJob() {
return jobs.get("lCJob")
.listener(jobListener)
.start(lCStep())
.build();
}

@Bean
public Step lCStep() {
return steps.get("lCStep")
.<String, String>chunk(1)
.reader(lCItemReader)
.processor(lCProcessor)
.writer(lCItemWriter)
.listener(promotionListener())
.build();
}

聆听者

@Bean
public ExecutionContextPromotionListener promotionListener() {
ExecutionContextPromotionListener executionContextPromotionListener = new ExecutionContextPromotionListener();
executionContextPromotionListener.setKeys(new String[]{"npag"});
return executionContextPromotionListener;
}

最佳答案

ExecutionContextPromotionListener 特别指出它在步骤结束时工作,以便在编写器执行之后。因此,我认为您所指望的促销事件并不会在您认为发生时发生。

如果我是你,我会在步骤上下文中设置它,并从步骤中获取它(如果你需要在一个步骤中使用该值)。否则我会将其设置为作业上下文。

另一个方面是@BeforeStep。这标志着在步骤上下文存在之前执行的方法。您在读取器中设置 nPag 值的方式是在步骤开始执行之后。

关于 Spring 批处理 : pass data between reader and writer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32736377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com