从数据库读取后将数据从一个编写器传递给另一个编写器

Pass data from one writer to another writer after reading from DB

我必须创建一个批处理作业,我需要从 1 个数据库中获取数据,并在处理后将该数据转储到另一个数据库,其中自动生成的 ID 将分配给持久化数据。我需要将该数据连同生成的 ID 一起发送到安慰队列。

Reader(DB1) --data1--> 处理器 --data2--> Writer (DB2) --data3--> 作家(安慰出版社)

我正在使用 spring boot-2.2.5.RELEASE 和 spring-boot-starter-batch.

我创建了一个包含 1 个步骤的作业,分别通过 RepositoryItemReader 和 RepositoryItemWriter 从 DB1 读取数据并向 DB2 写入数据。这工作正常。

现在下一个任务是将生成 ID 的持久数据发送到安慰流(使用 spring-cloud-starter-stream-solace)。

我有以下问题。请帮忙,因为我是 spring batch

的新手

根据某个参数保存到DB2后如何获取完整的记录?我必须编写自己的具有 StepExecution 上下文的 RepositoryItemWriter 还是可以以某种方式使用现有的 RepositoryItemWriter。

获得记录后,我需要使用安慰流,并且我有发布方法,该方法期望发布参数(记录)。我又想我需要编写自己的 Item Writer,或者我可以使用 StepExecutionContext 从上面的 repositoryItemWriter 传递的记录,或者我应该根据一些参数直接从这里查询到 DB2 吗?

以上两种情况我都需要使用 stepexecution 上下文,但我可以使用可用的 RepositoryItemWriter 还是必须自己编写?

除了使用上述方法之外,还有其他方便的概念吗?

将数据传递给后续步骤是 Spring Batch 中的常见模式。根据文档 https://docs.spring.io/spring-batch/docs/current/reference/html/common-patterns.html#passingDataToFutureSteps,您可以使用 stepExecution 来存储和检索生成的 ID。在您的情况下,编写者也是侦听器,它具有使用 @BeforeStep 注释的 before step 方法。例如:

public class DB2ItemWriter implements ItemWriter<Object> {
    private StepExecution stepExecution;

    public void write(List<? extends Object> items) throws Exception {
        // ...

        ExecutionContext stepContext = this.stepExecution.getExecutionContext();
        stepContext.put("generatedIds", ids);
    }

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

然后在下一个编写器中检索 ID

public class SolacePublisherItemWriter implements ItemWriter<Object> {

    public void write(List<? extends Object> items) throws Exception {
        // ...
    }

    @BeforeStep
    public void retrieveGeneratedIds(StepExecution stepExecution) {
        ExecutionContext stepExecutionContext = stepExecution.getExecutionContext();
        this.generatedIds = stepExecutionContext.get("generatedIds");
    }
}

I have created a job having 1 step that read data from DB1 and write data to DB2 via RepositoryItemReader and RepositoryItemWriter respectively. This is working fine.

我会添加第二个步骤,从 table 中读取数据(其中记录已由步骤 1 保存并生成它们的 ID)并使用自定义编写器将其推送到安慰。