0Pricing
Spring Boot 4 Complete Guide · บทเรียน

โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด

เชื่อมต่อคอมโพเนนต์ ItemReader, ItemProcessor และ ItemWriter สำหรับการประมวลผลเป็นชุดที่ขยายระบบได้

โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Chunk-Oriented Processing?

Spring Batch reads, processes, and writes data in chunks instead of one record at a time. A chunk is a configurable number of items (the commit-interval) handled inside a single transaction.

  • Read N items one by one with an ItemReader.
  • Process each item with an ItemProcessor.
  • Write the whole batch of N at once with an ItemWriter.

Writing in bulk and committing per chunk is what makes batch jobs scale to millions of rows without exhausting memory.

The Three Core Interfaces

Every chunk step is built from three single-method interfaces. Knowing their contracts is the foundation of the whole pattern.

  • ItemReader<I> → I read() returns the next item, or null when the input is exhausted.
  • ItemProcessor<I, O> → O process(I item) transforms an input into an output; returning null filters the item out.
  • ItemWriter<O> → void write(Chunk<? extends O> chunk) persists the accumulated chunk.
public interface ItemReader<I> {
    I read() throws Exception; // null = end of input
}

public interface ItemProcessor<I, O> {
    O process(I item) throws Exception; // null = filter
}

public interface ItemWriter<O> {
    void write(Chunk<? extends O> chunk) throws Exception;
}

Defining a Domain Type

A chunk step flows typed data from reader to processor to writer. Let's model a simple input and output. The reader emits raw Customer records and the writer stores normalized ones.

Using a Java record keeps these immutable value types concise. This snippet is plain Java with no framework, so it runs standalone.

public class DomainDemo {
    record Customer(String name, String email) {}

    public static void main(String[] args) {
        Customer c = new Customer("  Ada ", "ADA@MAIL.COM");
        Customer normalized = new Customer(
                c.name().trim(),
                c.email().toLowerCase());
        System.out.println(normalized);
    }
}

Building the ItemReader

For database input, JdbcCursorItemReader streams rows one at a time so memory stays flat. You give it a DataSource, a SQL query, and a RowMapper to turn each row into a domain object.

Spring Batch calls read() repeatedly until it returns null, advancing the cursor each time.

@Bean
public JdbcCursorItemReader<Customer> reader(DataSource dataSource) {
    return new JdbcCursorItemReaderBuilder<Customer>()
            .name("customerReader")
            .dataSource(dataSource)
            .sql("SELECT name, email FROM customers WHERE active = true")
            .rowMapper((rs, rowNum) ->
                    new Customer(rs.getString("name"), rs.getString("email")))
            .build();
}

Building the ItemProcessor

The processor is where business logic lives: validation, enrichment, transformation, or filtering. Its input and output types may differ.

  • Return a transformed object to pass it downstream.
  • Return null to skip the item entirely — it never reaches the writer.

Keep processors stateless and idempotent so they behave correctly when chunks are retried.

@Bean
public ItemProcessor<Customer, Customer> processor() {
    return customer -> {
        if (customer.email() == null || !customer.email().contains("@")) {
            return null; // filter invalid records out of the chunk
        }
        return new Customer(
                customer.name().trim(),
                customer.email().toLowerCase());
    };
}

Building the ItemWriter

The writer receives the whole processed chunk at once via a Chunk<O>. Writing in bulk — one batched INSERT per chunk instead of one per row — is the key performance win.

JdbcBatchItemWriter uses a parameterized SQL statement and a bean-property parameter source to map fields automatically.

@Bean
public JdbcBatchItemWriter<Customer> writer(DataSource dataSource) {
    return new JdbcBatchItemWriterBuilder<Customer>()
            .dataSource(dataSource)
            .sql("INSERT INTO customers_clean (name, email) VALUES (:name, :email)")
            .beanMapped()
            .build();
}

Wiring the Chunk Step

A Step ties the three components together. The generic types <Customer, Customer> declare the input and output of the chunk, and the integer is the commit-interval.

With a chunk size of 100, Spring Batch reads 100 items, processes each, then writes all survivors in one transaction before committing.

@Bean
public Step chunkStep(JobRepository jobRepository,
                      PlatformTransactionManager txManager,
                      ItemReader<Customer> reader,
                      ItemProcessor<Customer, Customer> processor,
                      ItemWriter<Customer> writer) {
    return new StepBuilder("chunkStep", jobRepository)
            .<Customer, Customer>chunk(100, txManager)
            .reader(reader)
            .processor(processor)
            .writer(writer)
            .build();
}

Assembling the Job

A Job is an ordered set of steps. For a single chunk step, the job simply starts with it. Spring Boot auto-detects the Job bean and runs it on startup.

The JobRepository records execution metadata — status, read/write counts, and the last committed position — enabling restartability.

@Bean
public Job importCustomersJob(JobRepository jobRepository, Step chunkStep) {
    return new JobBuilder("importCustomersJob", jobRepository)
            .start(chunkStep)
            .build();
}

Choosing the Chunk Size

The commit-interval is a tuning lever, not a magic number.

  • Too small (e.g. 1): one transaction per row — high commit overhead, slow.
  • Too large (e.g. 100,000): bigger transactions, more memory and rollback cost if a chunk fails.
  • Typical sweet spot: 100–1000, tuned by measuring throughput against your database and row size.

Remember: a failed item rolls back the entire chunk, so larger chunks mean more work redone on failure.

Fault Tolerance: Skip and Retry

Real input is messy. Wrap the step with .faultTolerant() to keep processing despite isolated failures.

  • .skip(...) — tolerate up to skipLimit bad items instead of failing the job.
  • .retry(...) — re-attempt transient errors (e.g. deadlocks) up to retryLimit before giving up.

On a skip or retry, Spring Batch re-scans the chunk item by item, isolating the offending record.

@Bean
public Step faultTolerantStep(JobRepository jobRepository,
                              PlatformTransactionManager txManager,
                              ItemReader<Customer> reader,
                              ItemProcessor<Customer, Customer> processor,
                              ItemWriter<Customer> writer) {
    return new StepBuilder("ftStep", jobRepository)
            .<Customer, Customer>chunk(100, txManager)
            .reader(reader)
            .processor(processor)
            .writer(writer)
            .faultTolerant()
            .skip(FlatFileParseException.class)
            .skipLimit(20)
            .retry(DeadlockLoserDataAccessException.class)
            .retryLimit(3)
            .build();
}

The Chunk Lifecycle in Order

Putting it together, each chunk follows the same loop inside one transaction:

  • 1. Read: call read() repeatedly until chunk-size items are buffered (or null ends input).
  • 2. Process: call process() on each item; nulls are filtered out.
  • 3. Write: pass the surviving items as one Chunk to write().
  • 4. Commit: commit the transaction and record progress in the JobRepository.

Then the loop repeats for the next chunk until the reader is exhausted.

Quick Check

Test your understanding of the chunk pipeline.

Recap

You wired a complete chunk-oriented flow in Spring Batch:

  • ItemReader streams input one item at a time, returning null at the end.
  • ItemProcessor transforms or filters items; null drops an item.
  • ItemWriter persists the whole chunk in bulk for performance.
  • The Step binds them with a chunk(size, txManager) commit-interval, and the Job orchestrates the steps.
  • Tune chunk size for throughput, and add .faultTolerant() with skip/retry for resilient pipelines.

This read-process-write loop, committed per chunk, is the backbone of scalable batch processing.

คำถามที่พบบ่อย

บทเรียน “โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด”

เชื่อมต่อคอมโพเนนต์ ItemReader, ItemProcessor และ ItemWriter สำหรับการประมวลผลเป็นชุดที่ขยายระบบได้ คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. งาน ขั้นตอน และโมเดล JobRepository
  2. โฟลว์ตัวอ่าน-ตัวประมวลผล-ตัวเขียนแบบแบ่งเป็นชุด
  3. ความทนทานต่อข้อผิดพลาด การข้าม และนโยบายการลองใหม่
  4. การแบ่งพาร์ทิชันและการทำงานขั้นตอนแบบขนาน
← กลับไปที่ Spring Boot 4 Complete Guide