0Pricing
Spring Boot 4 Microservices & REST APIs · Lección

Lectores, procesadores y escritores

Cree el flujo de procesamiento por lotes orientado a chunks

Lectores, procesadores y escritores es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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

Preguntas frecuentes

¿La lección «Lectores, procesadores y escritores» es gratis?

Sí — el texto completo de «Lectores, procesadores y escritores» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.

¿Qué aprenderé en «Lectores, procesadores y escritores»?

Cree el flujo de procesamiento por lotes orientado a chunks Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?

No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Lectores, procesadores y escritores»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?

Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Programación con @Scheduled
  2. Trabajos y pasos de Spring Batch
  3. Lectores, procesadores y escritores
  4. Reinicio y gestión de errores
← Volver a Spring Boot 4 Microservices & REST APIs