我有一个小的示例 Spring Batch 应用程序,第一次启动时可以正常工作,但是每当我关闭应用程序并重新启动 jar 时,我总是会收到此错误:
Caused by: org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT into BATCH_JOB_INSTANCE(JOB_INSTANCE_ID, JOB_NAME, JOB_KEY, VERSION) values (?, ?, ?, ?)]; Duplicate entry '1' for key 1; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 1
我不确定我的工作增量器设置是否错误。但就像我说的那样,我可以启动它然后使用 Web 服务 url/jobLauncher.html
来调用批处理任意次数就好了。只有在我关闭应用程序并重新启动它之后,我才会收到此错误。它想将 id 1 用于作业执行表,但 id 1 在之前的运行中已经存在。
主班
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, new String[]{ "date=" + System.currentTimeMillis() });
}
}
网络服务类
@Controller
public class JobLauncherController {
@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;
@RequestMapping("/jobLauncher.html")
@ResponseBody
public String handle() throws Exception{
jobLauncher.run(job, new JobParametersBuilder().addString("date", System.currentTimeMillis() + "").toJobParameters());
return "Started the batch...";
}
}
Spring Batch 类
@Configuration
@EnableBatchProcessing
public class SampleBatchApplication {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Bean
protected Tasklet tasklet() {
return new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext context) {
return RepeatStatus.FINISHED;
}
};
}
@Bean
public Job job() throws Exception {
return this.jobs.get("job")
.incrementer(new RunIdIncrementer())
.flow(this.step1())
.end()
.build();
}
@Bean
protected Step step1() throws Exception {
return this.steps.get("step1").tasklet(this.tasklet()).build();
}
@Bean
public DataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
try {
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUsername("test");
ds.setPassword("test");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/spring-batch");
} catch (Exception e) {
e.printStackTrace();
}
return ds;
}
}