multithreading - StoredProcedureItemReader 多线程异常
问题描述
我正在使用 Spring Batch StoredProcedureItemReader 检索结果集并将其插入到另一个使用 JpaItemWriter 的数据库中。下面是我的代码配置。
@Bean
public JdbcCursorItemReader jdbcCursorItemReader(){
JdbcCursorItemReader jdbcCursorItemReader = new JdbcCursorItemReader();
jdbcCursorItemReader.setSql("call myProcedure");
jdbcCursorItemReader.setRowMapper(new MyRowMapper());
jdbcCursorItemReader.setDataSource(myDataSource);
jdbcCursorItemReader.setFetchSize(50);
jdbcCursorItemReader.setVerifyCursorPosition(false);
jdbcCursorItemReader.setSaveState(false);
return jdbcCursorItemReader;
}
@Bean
public Step step() {
threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(50);
threadPoolTaskExecutor.setMaxPoolSize(100);
threadPoolTaskExecutor.setThreadNamePrefix("My-TaskExecutor ");
threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(Boolean.TRUE);
threadPoolTaskExecutor.initialize();
return stepBuilderFactory.get("myJob").transactionManager(secondaryTransactionManager)
.chunk(50).reader(jdbcCursorItemReader())
.writer(myJpaItemWriter())
.taskExecutor(threadPoolTaskExecutor)
.throttleLimit(100)
.build();
}
该代码在没有多线程或 threadpooltaskexecutor 的情况下工作正常。但是,在使用它们时我遇到以下错误。
Caused by: java.sql.SQLDataException: Current position is after the last row
could not execute statement [n/a] com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint
我试过使用 JdbcCursotItemReader,即使那样我也面临同样的错误。关于如何使这项工作的任何建议
解决方案
JdbcCursorItemReader
不是线程安全的,因为它基于一个ResultSet
不是线程安全的。StoredProcedureItemReader
也基于 a ,因此ResultSet
它也不是线程安全的。见https://stackoverflow.com/a/53964556/5019386
尝试使用JdbcPagingItemReader
which是线程安全的,或者如果您真的必须使用StoredProcedureItemReader
,则通过将其包装在SynchronizedItemStreamReader
.
希望这可以帮助。
推荐阅读
- angular - Angular 2+,异步测试和 setTimeout
- c++ - C++ Eclipse:二进制搜索树节点-> 数据 = 变量似乎不起作用
- kotlin - 为什么每个辅助构造函数都需要委托给 Kotlin 中的主构造函数?
- android - Android 模拟器在 Ubuntu 18.04 上使用 SIGSEGV 崩溃
- apache-spark - 如何使用 Spark Dataframe 读写 Cassandra 表?
- php - 在 PHP 中使用正则表达式更改文件链接路径结构
- android - 混合版本可能导致运行时崩溃,没有解决方案工作
- c - 分段错误:使用调用“ls”时为 11
- e-commerce - 在 sap hybris Ecommerce 中添加新语言资源包所需的步骤。
- javascript - Angular 5 [隐藏] 没有完全工作