【问题标题】:DuplicateKey Exception while trying to run the batch job on multiple Instances尝试在多个实例上运行批处理作业时出现 DuplicateKey 异常
【发布时间】:2020-07-10 13:47:03
【问题描述】:

我正在使用相同参数同时在集群中运行批处理作业。虽然,它只在一个实例上运行很好,但我得到的例外是:

Detail: Key (job_name, job_key)=(offlineTicketRefreshJob, c5d36835a13fd8ae0e91a69a6fa1c2d8) already exists.; nested exception is org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "job_inst_un"

我期待它会给出 JobAlreadyRunningException 或其他。我认为隔离级别对于批处理作业存储库也是可序列化的,那么为什么它会给出 PSQLException?

【问题讨论】:

    标签: java spring spring-boot spring-batch spring-scheduled


    【解决方案1】:

    如果您在作业存储库上正确配置了隔离级别,则不会发生这种情况。您没有分享您的作业存储库配置,但您可以在 Configuring a JobRepositoryTransaction Configuration for the JobRepository 部分找到示例:

    // This would reside in your BatchConfigurer implementation
    @Override
    protected JobRepository createJobRepository() throws Exception {
       JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
       factory.setDataSource(dataSource);
       factory.setTransactionManager(transactionManager);
       factory.setIsolationLevelForCreate("ISOLATION_SERIALIZABLE");
       factory.setTablePrefix("BATCH_");
       factory.setMaxVarCharLength(1000);
       return factory.getObject();
    }
    

    积极的隔离级别可防止在集群环境中创建重复的作业实例。 SERIALIZABLEREAD_COMMITTED 应该可以工作。

    【讨论】:

    • 不是默认隔离是 SERIALIZABLE 如同一文档中所述,所以我没有配置 jobrepository 并使用默认值。
    • 是的,SERIALIZABLE 是默认值,postgres 支持它 (postgresql.org/docs/9.5/transaction-iso.html)。你用的是哪个版本的 postgres?
    • 我使用的是 12.0
    • 调试了代码,看起来它正在将 ISOLATION_DEFAULT 设置为在 postgres 中 read_committed 的隔离级别。如前所述,尝试配置 jobrepository,但由于我正在使用 JPAItemWriter 编写显示“TransactionRequiredException”的项目,因此没有正在进行的事务。
    • 默认为 SERIALIZABLE:github.com/spring-projects/spring-batch/blob/…。如果在调试时有 ISOLATION_DEFAULT,则应该在某处覆盖它。现在已经解决了,要让 JPAItemWriter 工作,您需要确保 Spring Batch 配置了 JpaTransactionManager,请参阅stackoverflow.com/questions/22509529
    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 2021-08-15
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多