ItemStream

ItemReadersItemWriters 都能很好地发挥各自的用途,但在两者之间有一个共同的顾虑,这就需要另一个接口。一般来说,作为批处理作业范围的一部分,需要打开和关闭读者和写入器,并且需要一种机制来持久化状态。ItemStream 接口服务于该目的,如下例所示:

Both ItemReaders and ItemWriters serve their individual purposes well, but there is a common concern among both of them that necessitates another interface. In general, as part of the scope of a batch job, readers and writers need to be opened, closed, and require a mechanism for persisting state. The ItemStream interface serves that purpose, as shown in the following example:

public interface ItemStream {

    void open(ExecutionContext executionContext) throws ItemStreamException;

    void update(ExecutionContext executionContext) throws ItemStreamException;

    void close() throws ItemStreamException;
}

在描述每个方法之前,我们应该提一下 ExecutionContext。实现 ItemStreamItemReader 客户端应该在进行任何 read 调用之前调用 open,以打开任何资源(例如文件)或获得连接。类似的限制适用于实现 ItemStreamItemWriter。如第 2 章中所述,如果在 ExecutionContext 中找到预期数据,则可以使用它来在初始状态之外的位置启动 ItemReaderItemWriter。相反,调用 close 是为了确保在 open 期间分配的任何资源都得到安全释放。调用 update 主要用于确保将当前持有的任何状态加载到提供的 ExecutionContext 中。此方法在提交之前调用,以确保在提交之前将当前状态持久化到数据库中。

Before describing each method, we should mention the ExecutionContext. Clients of an ItemReader that also implement ItemStream should call open before any calls to read, in order to open any resources such as files or to obtain connections. A similar restriction applies to an ItemWriter that implements ItemStream. As mentioned in Chapter 2, if expected data is found in the ExecutionContext, it may be used to start the ItemReader or ItemWriter at a location other than its initial state. Conversely, close is called to ensure that any resources allocated during open are released safely. update is called primarily to ensure that any state currently being held is loaded into the provided ExecutionContext. This method is called before committing, to ensure that the current state is persisted in the database before commit.

ItemStream 的客户端是 Step(来自 Spring Batch Core)的特殊情况下,将为每个 StepExecution 创建一个 ExecutionContext,以允许用户存储特定执行的状态,并期望如果重新启动相同的 JobInstance,则返回该状态。对于熟悉 Quartz 的人来说,语义与 Quartz JobDataMap 非常相似。

In the special case where the client of an ItemStream is a Step (from the Spring Batch Core), an ExecutionContext is created for each StepExecution to allow users to store the state of a particular execution, with the expectation that it is returned if the same JobInstance is started again. For those familiar with Quartz, the semantics are very similar to a Quartz JobDataMap.