Is it possible to read data from DB, process it and in ItemWriter send to another system using RestAPI (REST TEMPLATE) in Spring batch project? All I can see is fetch data and write it in a csv file.
Spring batch item writer rest API
6.7k Views Asked by shubham sharma At
2
There are 2 best solutions below
0

Of course! you can send the processed records to another system using REST call in ItemWriter.
Use the below code in your RestItemWriter
class.
private RestTemplate restTemplate;
@Override
public void write(@NonNull Chunk<? extends Payload> chunk) throws Exception {
for((Payload payload : chunk){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "xx-tokenString-xx");
HttpEntity<Payload> requestEntity = new HttpEntity<>(payload, headers);
try{
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.PATCH, requestEntity, Object.class);
LOGGER.info("Request hits the server {}", response.getBody());
} catch(HttpClientErrorException e){
LOGGER.error("HttpClientErrorException occured during connection {}", e.getMessage());
} catch (Exception e) {
LOGGER.error("Exception occured during connection {}", e.getMessage());
}
}
}
To make HTTP Patch
request using RestTemplate
, below configurations are mandatory, for other HTTP
calls you may ignore it.
@Bean
public RestTemplate restTemplate() {
LOGGER.info("restTemplate Bean has bean created");
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate;
}
You have to add the below dependency in pom.xml
to use CloseableHttpClient
, and HttpClients
.
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
It is possible to create your own custom
ItemWriter
.In your case, please add the
spring-boot-starter-web
dependency to either yourpom.xml
orbuild.gradle
Example:
More information about custom item writers here