dms*_*775 2 java mysql spring-batch
我的工作遇到了问题
我正在尝试从数据库读取记录并写入txt 文件。数据库包含 1.800.000 条记录,有 149 列,问题是 select 位于 jobConfig.xml 中的 bean 'mysqlItemReader' 中,但是,我认为 select 尝试加载 JVM 内存中的所有记录,然后我内存不足,使用 randtb.cliente limit 200000 它运行正常,但超过 500k 的记录我内存不足,如何避免此错误?谢谢!
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<import resource="Context.xml" />
<bean id="tutorial" class="extractor.main.Tutorial" scope="prototype" />
<bean id="itemProcessor" class="extractor.main.CustomItemProcessor" />
<batch:job id="helloWorldJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="mysqlItemReader" writer="flatFileItemWriter"
processor="itemProcessor" commit-interval="50">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="mysqlItemReader"
class="org.springframework.batch.item.database.JdbcCursorItemReader">
<property name="dataSource" ref="dataSource"/>
<property name="sql" value="select * from randtb.cliente"/>
<property name="rowMapper">
<bean class="extractor.main.TutorialRowMapper"/>
</property>
</bean>
<bean id="flatFileItemWriter" class=" org.springframework.batch.item.file.FlatFileItemWriter">
<property name="resource" value="file:target/outputfiles/employee_output.txt" />
<property name="lineAggregator">
<bean
class=" org.springframework.batch.item.file.transform.PassThroughLineAggregator" />
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
ResultSet默认情况下,MySql 将返回导致 OOM 异常的所有内容。为了让它不这样做,您需要设置JdbcCursorItemReader#setFetchSize(Integer.MIN_VALUE). PreparedStatement这将告诉 Spring Batch 在以及设置上设置该值PreparedStatement#setFetchDirection(ResultSet.FETCH_FORWARD)。这将告诉 MySql 流式传输数据,从而不会破坏堆栈。
因此,对于您的具体示例,您需要将ItemReader配置更改为:
<bean id="mysqlItemReader"
class="org.springframework.batch.item.database.JdbcCursorItemReader">
<property name="dataSource" ref="dataSource"/>
<property name="sql" value="select * from randtb.cliente"/>
<property name="fetchSize" value="#{T(java.lang.Integer).MIN_VALUE}"/>
<property name="rowMapper">
<bean class="extractor.main.TutorialRowMapper"/>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
您可以在其文档中详细了解 MySql 中的工作原理: https: //dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-implementation-notes.html(请参阅 ResultSet部分)。
| 归档时间: |
|
| 查看次数: |
6768 次 |
| 最近记录: |