Spring Boot 4 Microservices & REST APIs · Lekcja

Czytniki, procesory i zapisy

Buduj wsadowy przepływ przetwarzania porcjami

Lekcja 3 z 413 kroki

Czytniki, procesory i zapisy to bezpłatna lekcja Spring Boot 4 Microservices & REST APIs na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Microservices & REST APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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
Bezpłatny start

Ucz się Java dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
24
Lekcje
93

Często zadawane pytania

Czy lekcja „Czytniki, procesory i zapisy” jest bezpłatna?

Tak — pełny tekst „Czytniki, procesory i zapisy” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Microservices & REST APIs, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Co nauczysz się w „Czytniki, procesory i zapisy”?

Buduj wsadowy przepływ przetwarzania porcjami Ćwiczysz Spring Boot 4 Microservices & REST APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Microservices & REST APIs?

Nie wymagamy żadnego doświadczenia. Spring Boot 4 Microservices & REST APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Czytniki, procesory i zapisy”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Microservices & REST APIs?

Tak. Każda lekcja Spring Boot 4 Microservices & REST APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Harmonogramowanie za pomocą @Scheduled
  2. Zadania i kroki Spring Batch
  3. Czytniki, procesory i zapisy
  4. Ponowne uruchamianie i obsługa błędów
← Powrót do Spring Boot 4 Microservices & REST APIs