首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Batch 2.0 新特性深度解析:分區處理、註解配置、Java 5 支持與非順序執行

     編輯:Java 相關知識

四大核心升級維度

維度關鍵特性業務價值
Java 5+ 基線泛型、參數化類型、類型安全 API編譯期發現錯誤、減少強轉、代碼可讀性提升
非順序執行條件分支、暫停/恢復、並行 Step複雜作業流建模、人工審批節點、多核利用
可伸縮性遠程分區、本地分區海量數據並行處理、線性擴展吞吐
註解配置Reader/Writer/Processor/Listener 註解化零 XML、類型安全、IDE 重構友好

1. Java 5 泛型化 API

// Spring Batch 1.x
ItemReader reader = ...;
Object item = reader.read(); // 需強轉

// Spring Batch 2.0
ItemReader reader = ...;
Trade trade = reader.read(); // 類型安全

// 自定義 Reader
@Component
public class TradeItemReader implements ItemReader {
    @Override
    public Trade read() { ... }
}

2. 非順序執行:Job Flow 控制

條件分支

<job id="orderJob">
  <step id="validate" next="decide">...</step>
  <decision id="decide" decider="orderDecider">
    <next on="HIGH_VALUE" to="manualReview"/>
    <next on="STANDARD" to="autoProcess"/>
    <next on="FAILED" to="notifyError"/>
  </decision>
  <step id="manualReview" next="notify">...</step>
  <step id="autoProcess" next="notify">...</step>
  <step id="notifyError" next="end">...</step>
  <step id="notify">...</step>
</job>

JobExecutionDecider 實現業務規則決策,支持 FAILED 狀態下繼續執行補償邏輯。

暫停/恢復

<step id="waitApproval">
  <tasklet ref="waitApprovalTasklet"/>
  <stop on="PAUSED" restart="waitApproval"/> <!-- 外部觸發恢復 -->
</step>
  • 適用場景:人工審批、外部系統回調、合規檢查。
  • 恢復方式:JobOperator.restart(executionId) 或重新啟動 Job 參數相同。

並行 Step

<split id="parallelSplit" task-executor="batchTaskExecutor" next="aggregate">
  <flow>
    <step id="stepA" next="stepB"/>
    <step id="stepB"/>
  </flow>
  <flow>
    <step id="stepC"/>
  </flow>
  <flow>
    <step id="stepD"/>
  </flow>
</split>

獨立 Step 併行執行,需配置 TaskExecutor(如 SimpleAsyncTaskExecutor 或線程池)。

3. 可伸縮性:分區處理

遠程分區

  • 架構:Manager Step 讀取輸入源 → 分割為多個 StepExecution → 發送至 Worker 節點 (JMS/AMQP) → Worker 處理 → 異步回覆結果。
  • 優點:輸入源無需預知結構、動態負載均衡。
  • 依賴:Spring Integration (JMS Channel Adapter)。

本地分區

<step id="partitionStep">
  <partition step="workerStep" partitioner="rangePartitioner">
    <handler grid-size="10" task-executor="batchTaskExecutor"/>
  </partition>
</step>

<bean id="rangePartitioner" class="org.springframework.batch.core.partition.support.RangePartitioner">
  <property name="column" value="id"/>
  <property name="dataSource" ref="dataSource"/>
  <property name="table" value="orders"/>
</bean>
  • PartitionHandler + StepExecutionSplitter 核心接口。
  • 每個分區獨立運行完整 Step (Reader/Processor/Writer),無序列化瓶頸,擴展性優於遠程分區。
  • 適用:主鍵範圍分區、文件名分區、時間窗口分區。

4. 註解配置:零 XML 組件掃描

@Configuration
@EnableBatchProcessing
public class BatchConfig {

    @Bean
    @StepScope // 晚綁定 JobParameters
    public FlatFileItemReader reader(@Value("#{jobParameters['inputFile']}") Resource input) {
        return new FlatFileItemReaderBuilder()
            .name("tradeReader")
            .resource(input)
            .delimited()
            .names("id", "symbol", "price", "quantity")
            .targetType(Trade.class)
            .build();
    }

    @Bean
    public TradeProcessor processor() { return new TradeProcessor(); }

    @Bean
    public JdbcBatchItemWriter writer(DataSource ds) {
        return new JdbcBatchItemWriterBuilder()
            .dataSource(ds)
            .sql("INSERT INTO trade (id, symbol, price, qty) VALUES (:id, :symbol, :price, :quantity)")
            .beanMapped()
            .build();
    }

    @Bean
    public Step step1(StepBuilderFactory steps, ItemReader reader,
                      ItemProcessor processor, ItemWriter writer) {
        return steps.get("step1")
            .chunk(100)
            .reader(reader)
            .processor(processor)
            .writer(writer)
            .build();
    }

    @Bean
    public Job job(JobBuilderFactory jobs, Step step1) {
        return jobs.get("tradeJob")
            .start(step1)
            .build();
    }
}
  • @StepScope 支持 #{jobParameters[...]} 晚綁定,解決 Job 參數注入時機問題。
  • Spring Batch 2.0 引入 spring-batch-xml 命名空間,註解與 XML 可混用。

監控與指標增強

  • 每 Step 級別統計:read.count, write.count, filter.count, skip.read, skip.write, skip.process。
  • Tasklet 模式 Step 同樣記錄執行次數、耗時。
  • 指標暴露:Batch MBean + Micrometer/Prometheus 適配器。

遷移路線圖

  • Spring Batch 2.0 → 2.1:引入 Spring 3.0 依賴(保留 2.5.6 可選)、Spring Expression Language (SpEL) 晚綁定增強。
  • 企業級產品:SpringSource 計劃提供分區/遠程分區運行時、管理調度控制台。

總結

Spring Batch 2.0 確立了現代批處理框架基石:類型安全 API、靈活流控、水平擴展分區、聲明式註解配置。新專案直接使用 Spring Boot 3.x + Spring Batch 5.x,繼承並強化了這些核心能力(GraalVM 原生、虛擬線程、Observability 原生支援)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved