
BatchConfig.java
@Configuration
public class BatchConfig {
@Autowired
RestItemReader restItemReader;
@Autowired
ItemWriter restFileWriter;
@Autowired
ItemProcessor simpleJobProcessor;
@Bean
public Job job(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new JobBuilder("job", jobRepository)
.incrementer(new RunIdIncrementer())
.start(simpleChunkStepRest(jobRepository, transactionManager))
.build();
}
@Bean
public Step simpleChunkStepRest(JobRepository jobRepository, PlatformTransactionManager transactionManager) {
return new StepBuilder("Chunk Oriented Step", jobRepository)
.<String, String>chunk(10, transactionManager)
.reader(restItemReader)
.processor(simpleJSONJobProcessor)
.writer(restFileWriter)
.build();
}
}
Employee.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Employee {
private Integer id;
private String name;
private String location;
private Integer age;
}
SimpleJSONJobProcessor.java
@Component
public class SimpleJSONJobProcessor implements ItemProcessor<Employee, String> {
@Override
public String process(Employee item) throws Exception {
System.out.println("Inside JSON Job Processor");
String employeeDetails = "The Employee Name is " + item.getName() + ", his Age is " + item.getAge() + " and location is " + item.getLocation();
return employeeDetails;
}
}
RestItemReader.java
@Component
public class RestItemReader implements ItemReader {
@Autowired
EmployeeService employeeService;
private List<Employee> arrEmployee;
@Override
public Employee read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
if(arrEmployee == null){
arrEmployee = employeeService.getEmpList();
}
if(arrEmployee != null && !arrEmployee.isEmpty()){
return arrEmployee.remove(0);
}
return null;
}
}
EmployeeService.java
4
@Service
public class EmployeeService {
List<Employee> arrEmp = null;
public List<Employee> getEmpList(){
RestTemplate restTemplate = new RestTemplate();
Employee[] employeeArray = restTemplate.getForObject("http://localhost:8080/employee", Employee[].class);
List<Employee> arrEmp = Arrays.stream(employeeArray)
.collect(Collectors.toCollection(ArrayList::new));
return arrEmp;
}
public Employee getEmployee(){
if(arrEmp == null){
getEmpList();
}
if(arrEmp != null && !arrEmp.isEmpty()){
return getEmpList().remove(0);
}
return null;
}
}
RestFileWriter.java
@Component
public class RestFileWriter implements ItemWriter<String> {
@Override
public void write(Chunk<? extends String> items) throws Exception {
System.out.println("Inside Job Writer");
items.getItems().forEach(System.out::println);
}
}
Output
Inside JSON Job Processor Inside JSON Job Processor Inside JSON Job Processor Inside Job Writer The Employee Name is Mugil, his Age is 25 and location is Chennai The Employee Name is Mani, his Age is 25 and location is Bangalore The Employee Name is Shiva, his Age is 20 and location is Rajsatan