Spring Boot 4 Microservices & REST APIs · Lezione

Reader, processor e writer

Costruisca il flusso batch orientato ai chunk.

Lezione 3 di 413 passaggi

Reader, processor e writer è una lezione Spring Boot 4 Microservices & REST APIs gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Microservices & REST APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

The read-process-write triad

A chunk step has three collaborators:

  • ItemReader - supplies items one at a time
  • ItemProcessor - transforms or filters an item
  • ItemWriter - persists a chunk of items

ItemReader interface

ItemReader.read() returns the next item, or null when the input is exhausted. Spring Batch keeps calling it until it returns null.

public interface ItemReader<T> {
    T read() throws Exception;
}

FlatFileItemReader

For CSV files, FlatFileItemReader reads lines and maps them to objects via a line mapper.

@Bean
public FlatFileItemReader<Person> reader() {
    return new FlatFileItemReaderBuilder<Person>()
            .name("personReader")
            .resource(new ClassPathResource("people.csv"))
            .delimited()
            .names("firstName", "lastName")
            .targetType(Person.class)
            .build();
}

JdbcCursorItemReader

To read from a database, use JdbcCursorItemReader or JdbcPagingItemReader. Paging is preferred for very large result sets to avoid holding a long cursor.

@Bean
public JdbcCursorItemReader<Person> dbReader(DataSource ds) {
    return new JdbcCursorItemReaderBuilder<Person>()
            .name("dbReader")
            .dataSource(ds)
            .sql("SELECT first_name, last_name FROM people")
            .rowMapper(new PersonRowMapper())
            .build();
}

ItemProcessor interface

ItemProcessor transforms an input item into an output item. The input and output types can differ.

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

Writing a processor

Here a processor uppercases names. Returning a transformed object is the common case.

public class UpperCaseProcessor implements ItemProcessor<Person, Person> {
    @Override
    public Person process(Person p) {
        return new Person(p.getFirstName().toUpperCase(),
                          p.getLastName().toUpperCase());
    }
}

Filtering with the processor

If a processor returns null, the item is filtered out and never reaches the writer. This is how you skip records based on business rules.

public Person process(Person p) {
    if (p.getLastName().isBlank()) {
        return null; // drop this record
    }
    return p;
}

ItemWriter interface

ItemWriter receives a chunk of items at once, not single items. This lets it batch the write into one efficient operation.

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

JdbcBatchItemWriter

JdbcBatchItemWriter performs a batched SQL insert/update for the whole chunk, which is far faster than row-by-row writes.

@Bean
public JdbcBatchItemWriter<Person> writer(DataSource ds) {
    return new JdbcBatchItemWriterBuilder<Person>()
            .dataSource(ds)
            .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
            .beanMapped()
            .build();
}

Wiring them into a step

The step ties the triad together with a chunk size. Items flow reader -> processor -> writer in chunks.

return new StepBuilder("step1", repo)
        .<Person, Person>chunk(50, tx)
        .reader(reader())
        .processor(new UpperCaseProcessor())
        .writer(writer(ds))
        .build();

Custom readers and writers

You can implement the interfaces directly for custom sources (a REST API, a queue). Spring also offers ItemStream so your component can save and restore its position for restarts.

Quick Check

Verify your understanding of the triad.

Recap

You assembled a chunk pipeline:

  • ItemReader.read() returns items until null
  • ItemProcessor transforms; returning null filters
  • ItemWriter writes a whole Chunk at once
  • The step binds all three with a chunk size
Gratis per iniziare

Impara Java con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
24
Lezioni
93

Domande Frequenti

La lezione «Reader, processor e writer» è gratuita?

Sì — il testo completo di «Reader, processor e writer» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Microservices & REST APIs, passa a CoddyKit PRO. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Cosa imparerò in «Reader, processor e writer»?

Costruisca il flusso batch orientato ai chunk. Eserciti Spring Boot 4 Microservices & REST APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Boot 4 Microservices & REST APIs?

Non è richiesta alcuna esperienza precedente. Spring Boot 4 Microservices & REST APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Reader, processor e writer»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Microservices & REST APIs?

Sì. Ogni lezione Spring Boot 4 Microservices & REST APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Pianificazione con @Scheduled
  2. Job e step di Spring Batch
  3. Reader, processor e writer
  4. Riavvio e gestione degli errori
← Torna a Spring Boot 4 Microservices & REST APIs