在 spring 批次中所有重试都用完后如何执行一些代码?

How to execute some code after all retries are exhausted in spring batch?

我已将最大重试次数设置为 3。我只添加了 RemoteAccessException 作为可重试异常。我想要做的是将某些实体的状态更改为错误,并在所有重试都用完后将它们保存到数据库中。所有这一切都是我在作家的步骤中做的。我已经实现了 ItemWriteListener 并且当 RemoteAccessException 发生时,它确实转到 onWriteError 方法,我在其中写了这个状态变化 logic.But 当我在所有执行完成后检查数据库时,我发现状态根本没有改变。

我的问题是,在这种情况下到底发生了什么?重试 3 次后,整个步骤是否回滚,因为异常仍然存在,所以数据库中没有任何更改?而且,我确实需要将状态更改为错误。有什么办法可以实现吗?

我找到了这个问题的答案。在我的例子中,发生了什么 - RetryExhaustedException 在 3 次重试后被抛出。正如 Spring 重试文档中所述,在这种情况下,任何封闭事务都将回滚。

来自 spring 文档(https://docs.spring.io/spring-batch/trunk/reference/html/retry.html)-

After a callback fails the RetryTemplate has to make a call to the RetryPolicy to ask it to update its state (which will be stored in the RetryContext), and then it asks the policy if another attempt can be made. If another attempt cannot be made (e.g. a limit is reached or a timeout is detected) then the policy is also responsible for handling the exhausted state. Simple implementations will just throw RetryExhaustedException which will cause any enclosing transaction to be rolled back. More sophisticated implementations might attempt to take some recovery action, in which case the transaction can remain intact.

对于需要将状态更改为错误的情况,我问过类似的问题并找到了答案-