【问题标题】:SpringBatch Reading and Writing in chunksSpring Batch 分块读写
【发布时间】:2023-03-25 11:04:01
【问题描述】:

我有一个包含一些 for 循环的程序。该程序的想法是使用多个帐户登录一个网站并检索一个列表(每次登录都会带来一个不同的列表)。所以我设置它的方式是使用增强的 for 循环:

loginsList.put( "firstUsername", "firstPassword" );
loginsList.put( "secondUsername", "secondPassword" );
loginsList.put( "thirdUsername", "thirdPassword" );
loginsList.put( "fourthUsername", "fourthPassword" );
loginsList.put( "fifthUsername", "fifthPassword" );

for ( Entry<String, String> nextLogin : logins.entrySet() ) {
    String nextUser = nextLogin.getKey();
    String nextPass = nextLogin.getValue();

    Response authenticateUserResponse = Jsoup.connect( WEBSITE_I_NEED_TO_LOGIN_TO )
            .data( "username", nextUser )
            .data( "password", nextPass )
            .execute();

基本上这就是我想要的流程:

read()--> 获取列表----> 将列表发送到 write() 方法以将其写入数据库--> 循环并获取下一个登录信息-->read()--> 获取list--> 将其发送到 write()..etc..

但是我遇到的问题是我的循环在读取方法中运行,并且在所有帐户中遍历所有列表之前不会转到写入方法。本质上,写入最后只被调用一次,所以我现在拥有的是这样的(这是有缺陷的设计):

read()--->获取列表-->下一个账户--->获取列表---下一个账户--->获取列表--->write()

在我只读取一个块之后,如何在 Spring 中组织块处理来写入?

【问题讨论】:

    标签: java spring spring-batch


    【解决方案1】:
    for ( Entry<String, String> nextLogin : logins.entrySet() ) {
        String nextUser = nextLogin.getKey();
        String nextPass = nextLogin.getValue();
         //do something
           ......
         //call write function 
    writeValues(x, y, z); 
    }
    

    这就是你想要的吗? 否则它看起来就像一个传统的 SpringBatch:Read > Process > Proceeed 案例。 您将拥有您的读者 = 获得记录 处理器 > 保存记录

    如果没有错误,Spring 批处理会将您移至下一条记录。

        <step id="processUpdates">
            <tasklet task-executor="batchThreadPoolTaskExecutor" throttle-limit="${batch.cviscoreupdate.threadcount}">
                <chunk reader="Reader" processor="ItemProcessor" writer="ItemWriter" commit-interval="${batch.commit.interval}" skip-limit="${batch.skip.limit}" >
                    <skippable-exception-classes>
                        <include class="batch.support.SkipRecordException" />
                    </skippable-exception-classes>
                </chunk>
            </tasklet>
            <next on="FAILED" to="errorExit"/>          
            <next on="*" to="moveFilesFromWorkToDone" />
            <listeners>
                <listener ref="UpdateSkipListener"/>
            </listeners>
        </step>
    
    <bean id="CVIScoreUpdateItemProcessor" class="com.batch.MyUpdateItemProcessor" scope="step" init-method="init" />
    

    【讨论】:

    • 你需要这样的步骤
    • 所以你的意思是如果它保存记录然后自动调用作者?
    • 好吧,是的,不是的,就像你想做的那样,我会保存到处理器内的数据库中。 Writer 传统上会写入该记录。但同样,Processor 和 Writer 是您编写的类。见编辑
    • 对...在我保存到数据库后,作者运行,我只调用一次
    • 是的,所以把它放到处理器中,处理器会为记录集中的每条记录运行。
    猜你喜欢
    • 2012-12-07
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多