Spring Batch is a web application that collects and stores large amounts of customer data. You want to perform various operations on this data like importing resources, validating and transforming data and then exporting or storing it in other resources, all conducted in a batch format.
Here in this scenario, we can use Spring Batch as it provides features to process the data in a batch like automating the process, handling errors, reading data, validating data and then exporting it to resources.
Spring Batch is a lightweight batch processing framework useful for processing large numbers of records. It also provides features that support extremely high volume and high-performance batch jobs through its optimization and partitioning techniques.
1. Robust and Scalable: It’s designed to process large volumes of data and process data in chunks reducing memory usage and improving performance. It also provides parallel processing that enables concurrent execution of tasks.
2. Fault-Tolerant: It offers error-handling features to ensure the reliability of processing. It provides features like automatic restart, and skip/retry functionality. In case of failure, it recovers the execution state and resumes processing from that point of failure.
3. Monitoring: It provides built-in monitoring features that allow developers to track job progress like the number of records read, written and processed per file.
Related read: How To Improve Speed & Reliability Of A Product Using Monitoring Tools
1. Job: A job is a batch process that can be executed manually or scheduled. The job can contain one or more steps.
2. Step: A step is part of a job that consists of a reader, processor, writer, and listener.
3. Reader: The reader reads the data from different sources such as CSV, txt, db etc. It provides multiple built-in readers and we can create our own custom reader.
4. Processor: The processor is used for filtering, validating, and transforming the input data into the desired format required for writing.
5. Writer: The writer takes the data from the processor and stores it in a database, CSV etc. sources.
6. Listeners: The listeners allow developers to hook into the batch processing lifecycle and perform actions at specific events. Examples include before/after job execution, step execution, or chunk completion.
Spring Batch uses tables to store batch job information which contains information like files processed, number of rows processed, read, written, job status, and step status.
Let’s start implementing Spring Batch into our application. For that, we have to add Spring Batch dependency in pom.xml,
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency>
Now we will create a config file for the Spring Batch,
@Configuration public class EmployeeBatchConfig { @Value("${employee-batch.step-name}") private String stepName; @Value("${employee-batch.chunk-size}") private int chunkSize; @Value("${employee-batch.files-path}") private String filesPath; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private EmployeeProcessor employeeProcessor; @Autowired private EmployeeWriter employeeWriter; public Job runJob() throws IOException { return jobBuilderFactory.get("employee").incrementer(new RunIdIncrementer()).flow(employeeStep()).end().build(); } @Bean Step employeeStep() throws IOException { return stepBuilderFactory .get(stepName) .<Employee,EmployeeOutput>chunk(chunkSize) .reader(multiResourceItemreader()) .processor(employeeProcessor) .writer(employeeWriter) .build(); } @Bean public MultiResourceItemReader<Employee> multiResourceItemreader() throws IOException { MultiResourceItemReader<Employee> reader = new MultiResourceItemReader<>(); reader.setDelegate(employeeReader()); reader.setResources(getResources()); return reader; } private Resource[] getResources() throws IOException { ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver(); Resource[] resources = patternResolver.getResources("file:" + filesPath); return resources; } @Bean @StepScope FlatFileItemReader<Employee> employeeReader() throws MalformedURLException { FlatFileItemReader<Employee> reader = new FlatFileItemReader<>(); reader.setLinesToSkip(1); reader.setLineMapper(lineMapper()); return reader; } public LineMapper<Employee> lineMapper() { DefaultLineMapper<Employee> lineMapper = new DefaultLineMapper<>(); DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer(); lineTokenizer.setDelimiter(","); lineTokenizer.setStrict(false); lineTokenizer.setNames(getFileHeader()); lineMapper.setLineTokenizer(lineTokenizer); lineMapper.setFieldSetMapper(fieldSetMapper()); return lineMapper; } public FieldSetMapper<Employee> fieldSetMapper() { return new EmployeeInputMapper(); } public String[] getFileHeader() { return new String[] { "id", "name", "email", "gender", "age" }; } }
In the above config, we have created one job using JobBuilderFactory. The job contains one step. In that step, we have mentioned our reader, processor and writer. MultiResourceItemReader is used for reading multiple resources and that resource will be passed to FlatFileItemReader for reading. In the linemapper we have mentioned delimiter, file headers, and one input mapper for mapping data to the required object.
Now we will create a processor for processing the data after reading it from the given resource,
public class EmployeeProcessor implements ItemProcessor<Employee, EmployeeOutput> { @Override public EmployeeOutput process(Employee item) throws Exception { EmployeeOutput out = new EmployeeOutput(); out.setAge(item.getAge()); out.setDateOfBirth(getDateOfBirth(item.getAge())); out.setEmail(item.getEmail()); out.setGender(item.getGender().toUpperCase()); out.setId(item.getId()); out.setName(item.getName()); return out; } private String getDateOfBirth(int age) { LocalDate now = LocalDate.now(); LocalDate dob = now.minusYears(age); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); return dob.format(formatter); } }
Here for processing, we are converting employee to employee output and calculating its date of birth from age.
Now we will create one writer for storing employees in db,
public class EmployeeWriter implements ItemWriter<EmployeeOutput> { @Override public void write(List<? extends EmployeeOutput> items) throws Exception { employeeRepository.saveAll(items); items.forEach(e->{ System.out.println(e.getDateOfBirth()); }); } }
In this blog, we learned about Spring Batch, its components like job, step, reader, writer, processor and tables created by Spring Batch and how to read data from files using FlatFileReader, process data using ItemProcessor and write data to db or any other resources using ItemWriter.
In summary, now that you have this knowledge, you’re ready to use Spring Batch to make your web applications better at handling lots of data at once. Spring Batch is really good at this and can help your organization create high-speed and reliable data processing solutions. It’s like having a strong partner to assist you in achieving top-notch data processing results.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowLeave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.
Register HereThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork