Spring batch Spring批处理作业状态配置
当编写器抛出异常时,我希望能够将步骤和作业状态设置为失败。在调试和检查spring批处理源代码之后,我注意到RepeatTemplate配置了一个SimpleRetryExceptionHandler,它将BatchRuntimeException视为致命异常,因此将作业状态设置为FAILED,因此,我将编写器中的代码包装在一个try-catch中,它将RuntimeException包装在一个BatchRuntimeException中,现在作业和步骤状态设置为FAILED,正如我所希望的那样。不过,我不确定这是否是正确的方法,因为我在任何地方都找不到它的文档,BatchRuntimeException的文档也没有提到它。因此,问题是:这是正确的方法吗 我想到的另一件事是,如果写操作失败,作业失败是否有意义,但考虑到我的用例,我认为这是有意义的,就像这样:使用流读取器从数据库读取条目,流读取器将查询配置为针对数据库运行,然后使用流编写器通过电子邮件或http检索配置发送这些条目,并在流打开方法中向其中发送项目。如果一切都成功,则使用“已发送”状态更新数据库条目;如果在doOpen/open/write方法期间发生错误,则调用StepExecutionListener以发送作业失败的通知电子邮件。这就是我需要将作业状态设置为FAILED的原因之一,以便正确执行检查ExitCode是否失败的StepExecutionListener。第二个原因是我想使用spring Batch Admin应用程序来管理作业,如果作业显示为已完成,尽管写入失败,但这似乎有误导性,因为作业的全部目的是发送项目。这样,如果作业失败,可以重新启动作业,更改配置后,例如正确配置收件人电子邮件地址 另外,如果写调用失败,那么数据库中的条目应该将其状态更新为FAILED,我计划在新事务中的ItemWriteListener的onWriteError中执行此操作,因为当前条目将回滚 我发布了这么长的描述,只是为了确保我没有违背这里框架的意图,试图从编写者那里将作业状态设置为失败 期待着您对此的想法 您好, 克里斯蒂 注意:作业的配置如下:Spring batch Spring批处理作业状态配置,spring-batch,Spring Batch,当编写器抛出异常时,我希望能够将步骤和作业状态设置为失败。在调试和检查spring批处理源代码之后,我注意到RepeatTemplate配置了一个SimpleRetryExceptionHandler,它将BatchRuntimeException视为致命异常,因此将作业状态设置为FAILED,因此,我将编写器中的代码包装在一个try-catch中,它将RuntimeException包装在一个BatchRuntimeException中,现在作业和步骤状态设置为FAILED,正如我所希望的那样
<batch:job id="job">
<batch:step id="step">
<batch:tasklet>
<batch:chunk reader="reader" writer="writer" reader-transactional-queue="true" commit-interval="#{properties['export.page.size']}"/>
</batch:tasklet>
<batch:listeners>
<batch:listener ref="failedStepListener"/>
</batch:listeners>
</batch:step>
</batch:job>
稍后编辑:读写器配置如下:
<bean name="reader" class="...LeadsReader" scope="step">
<property name="campaignId" value="#{jobParameters[campaignId]}" />
<property name="partnerId" value="#{jobParameters[partnerId]}" />
<property name="from" value="#{jobParameters[from]}" />
<property name="to" value="#{jobParameters[to]}" />
<property name="saveState" value="false" /> <!-- we use a database flag to indicate processed records -->
</bean>
<bean name="writer" class="...LeadsItemWriter" scope="step">
<property name="campaignId" value="#{jobParameters[campaignId]}" />
</bean>
编写器的代码是:
public class LeadsItemWriter extends AbstractItemStreamItemWriter<Object[]> {
//fields and setters omitted
public LeadsItemWriter() {
setName(ClassUtils.getShortName(LeadsItemWriter.class));
}
@Override
public void open(ExecutionContext executionContext) {
super.open(executionContext);
PartnerCommunicationDTO partnerCommunicationDTO = this.leadableService.getByCampaignId(this.campaignId)
.getPartnerCommDTO();
this.transportConfig = partnerCommunicationDTO != null ? partnerCommunicationDTO.getTransportConfig() : null;
this.encoding = partnerCommunicationDTO != null ? partnerCommunicationDTO.getEnconding() : null;
if (this.transportConfig == null) {
throw new ItemStreamException ("Failed to retrieve the transport configuration for campaign id: "
+ this.campaignId);
}
PageRequestDTO pageRequestDTO = this.pageRequestMapper.map(partnerCommunicationDTO);
if (pageRequestDTO == null) {
throw new ItemStreamException("Wrong transport mapping configured for campaign id: " + this.campaignId);
}
this.columnNames = new ArrayList<>();
for (LeadColumnDTO leadColumnDTO : pageRequestDTO.getColumns()) {
this.columnNames.add(leadColumnDTO.getName());
}
}
@Override
public void write(List<? extends Object[]> items) throws Exception {
try {
if (this.transportConfig.getTransportType() == TransportConfigEnum.EMAIL) {
this.leadExporterService.sendLeads(items, this.columnNames, this.transportConfig, this.encoding);
} else {
for (Object[] lead : items) {
this.leadExporterService.sendLead(lead, this.columnNames, this.transportConfig, this.encoding);
}
}
} catch (RuntimeException e) {
LOGGER.error("Encountered exception while sending leads.", e);
//wrap exception so that the job fails and the notification listener gets called
throw new BatchRuntimeException(e);
}
}
}
读者代码:
public class LeadsReader extends AbstractPagingItemReader<Object[]> {
//fields and setters omitted
public LeadsReader() {
setName(ClassUtils.getShortName(LeadsReader.class));
}
@Override
protected void doOpen() throws Exception {
this.pageRequestDTO = this.pageRequestMapper.map(this.leadableService.getByCampaignId(this.campaignId)
.getPartnerCommDTO());
if (pageRequestDTO == null) {
throw new ItemStreamException("Wrong transport mapping configured for campaign id: " + this.campaignId);
}
this.timeInterval = new LeadTimeIntervalDTO(this.from != null ? of(this.from,
LeadQueryFilterParam.Comparison.GT) : null,
this.to != null ? of(this.to, LeadQueryFilterParam.Comparison.LE) : null);
super.doOpen();
}
private LeadFilterDTO of(Date date, LeadQueryFilterParam.Comparison comparison) {
LeadFilterDTO filterDTO = new LeadFilterDTO();
filterDTO.setColumn(CREATION_DATE);
filterDTO.setSqlType(DATE);
filterDTO.setComparison(comparison.name());
filterDTO.setValue(DateUtil.format(date, Validator.DATE_FORMAT));
return filterDTO;
}
@Override
protected void doReadPage() {
if (results == null) {
results = new CopyOnWriteArrayList<>();
} else {
results.clear();
}
if (this.pageRequestDTO != null) {
results.addAll(LeadsReader.this.leadStorageService.listLeads(
LeadsReader.this.pageRequestDTO.getColumns(),
LeadsReader.this.getFilters(),
LeadsReader.this.pageRequestDTO.getQueryOrderByParams(),
LeadsReader.this.pageRequestDTO.isUniqueByEmail(), LeadsReader.this.timeInterval,
(long) getPage() + 1, (long) getPageSize()).getExportedLeadsRows());
}
}
private List<LeadFilterDTO> getFilters() {
List<LeadFilterDTO> filtersList = new ArrayList<>();
LeadFilterDTO campaignFilter = new LeadFilterDTO();
campaignFilter.setColumn(CAMPAIGN_ID);
campaignFilter.setValue(Long.toString(campaignId));
campaignFilter.setSqlType(BIGINTEGER);
filtersList.add(campaignFilter);
LeadFilterDTO partnerFilter = new LeadFilterDTO();
partnerFilter.setColumn(PARTNER_ID);
partnerFilter.setValue(Long.toString(partnerId));
partnerFilter.setSqlType(BIGINTEGER);
filtersList.add(partnerFilter);
LeadFilterDTO statusFilter = new LeadFilterDTO();
statusFilter.setColumn(STATUS);
statusFilter.setValue("VALID");
statusFilter.setSqlType(CHAR);
filtersList.add(statusFilter);
return filtersList;
}
@Override
protected void doJumpToPage(int itemIndex) {
}
}如果框架内的组件(特别是ItemReader、ItemProcessor、ItemWriter或Tasklet)引发异常且未被捕获,则执行该组件的步骤将被标记为失败,而无需执行任何其他操作。如果一个步骤失败,作业也会被标记为失败,这就是允许重新启动作业的原因
简言之,当抛出异常时,您不需要做任何额外的事情来使作业失败 这并不完全适用于所有情况:例如,如果读卡器配置为reader transactional queue=true,则StepParserStepFactoryBean调用createFaultTolerantStep方法,该方法反过来使用createRetryOperations中的SimpleRetryExceptionHandler配置RepeatTemplate,该处理程序接受异常。当然,我已经在描述中添加了它们的配置。由于您使用的是自定义读写器,您能否也包含它们的代码?我已经将它们添加到描述中。嗨,伙计们,我最终遇到了类似的问题。基本上,我正在对我的步骤进行分区,我的编写器为所有分区抛出一个BatchRuntimeException。但我的工作状态已完成。我认为应该失败。此外,在我的批处理步骤中,执行表partition0失败,partition1失败,但最后一步显示为放弃