Java 复制 Spring Batch 作业实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19597683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:38:40  来源:igfitidea点击:

Duplicate Spring Batch Job Instance

javaspringspring-batchspring-boot

提问by Mark Spangler

I have a small sample Spring Batch application that when started for the first time will work fine but whenever I shut the application down & restart the jar I always get this error:

我有一个小示例 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

I'm not sure if I have the job incrementer setup wrong. But like I said I can start it up & then use the web service url, /jobLauncher.html, to invoke the batch process any number of times just fine. It's only after I shutdown the application & restart it that I get this error. It wants to use id 1 for the job execution table but id 1 is already there from the previous runs.

我不确定我的作业增量器设置是否错误。但就像我说的那样,我可以启动它,然后使用 Web 服务 url/jobLauncher.html调用批处理任意次数就好了。只有在我关闭应用程序并重新启动它之后,我才会收到此错误。它想将 id 1 用于作业执行表,但 id 1 已经存在于之前的运行中。

Main class

主班

@EnableAutoConfiguration
@ComponentScan
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, new String[]{ "date=" + System.currentTimeMillis() });
    }
}

Webservice class

网络服务类

@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 class

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;
    }
}

采纳答案by Mark Spangler

Found the issue. When using the @EnableAutoConfigurationannotation from Spring Boot it will invoke the org.springframework.boot.autoconfigure.batch.BatchAutoConfigurationclass which will initialize the database from the 'schema-mysql.sql' file.

发现问题。使用@EnableAutoConfigurationSpring Boot 中的注解时,它将调用org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration从“schema-mysql.sql”文件初始化数据库的类。

Inside the schema-mysql.sqlfile is some code to reset the sequence id's for the batch meta tables which is why I was getting a duplicate key error:

schema-mysql.sql文件中,有一些代码可以重置批处理元表的序列 ID,这就是为什么我收到重复键错误的原因:

INSERT INTO BATCH_STEP_EXECUTION_SEQ values(0);
INSERT INTO BATCH_JOB_EXECUTION_SEQ values(0);
INSERT INTO BATCH_JOB_SEQ values(0);

The fix was to build the Spring Batch tables separately & then change the @EnableAutoConfigurationannotation to:

解决方法是单独构建 Spring Batch 表,然后将@EnableAutoConfiguration注释更改为:

@EnableAutoConfiguration(exclude={BatchAutoConfiguration.class})

so that when the application starts up it will not try to initialize the Spring Batch tables.

这样当应用程序启动时,它就不会尝试初始化 Spring Batch 表。

To exclude or customize Spring Boot's auto-configuration for other components you can find some docs here: http://projects.spring.io/spring-boot/docs/spring-boot-autoconfigure/README.html

要为其他组件排除或自定义 Spring Boot 的自动配置,您可以在此处找到一些文档:http: //projects.spring.io/spring-boot/docs/spring-boot-autoconfigure/README.html

The BatchAutoConfiguration code: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java

BatchAutoConfiguration 代码:https: //github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java