Let's implement a non-blocking batch process by following these steps:
- Create a Spring Boot 2.0 project, ch11-batch-async, that has the same starter POM dependencies with the same MySQL connection pool support and Spring OXM module.
- Create a bootstrap class that enables batch processing and task scheduling:
@EnableBatchProcessing @SpringBootApplication @EnableScheduling public class AsyncBatchBootApplication { public static void main(String[] args) throws Exception { SpringApplication.run(AsyncBatchBootApplication.class, args); } }
- In its srcmain/ esources directory, create application.properties that contain the same configuration as the one in ch11-batch-sync. Just modify some server-related configurations.
- Copy logback.xml from the previous project and drop it inside srcmain esources to enable logging.
- Then, copy all the packages from the ch11-batch-sync project without any changes.
- Next, start the asynchronous batch processing configuration and inject the TaskExecutor that will generate the thread pool into BatchConfig:
@Bean("mvcTaskexecutor") public TaskExecutor getAsyncExecutor() { ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor( Executors.newFixedThreadPool(100)); executor.setTaskDecorator(new TaskDecorator() { @Override public Runnable decorate (Runnable runnable) { return () -> { long t = System.currentTimeMillis(); runnable.run(); System.out.printf("Thread %s has a processing time: %s%n", Thread.currentThread().getName(), (System.currentTimeMillis() - t)); }; } }); return executor; }
- Assign threads to taskletStep() and chunkStep() by passing the TaskExecutor bean to the taskExecutor() method of their respective StepBuildFactory instances.
- Save all files. Deploy the application with clean spring-boot:run Maven command. Expect random and messy writes to the output.txt output file.