I am trying to implement a streaming ReST endpoint in my controller:
@GetMapping("/stream")
public ResponseEntity<StreamingResponseBody> streamData() {
Stream<Data> data = service.streamData();
StreamingResponseBody responseBody = httpResponseOutputStream -> {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(httpResponseOutputStream))) {
data.forEach(d -> {
try {
writer.write(gson.toJson(d));
writer.flush();
} catch (IOException exception) {
logger.error("exception occurred while writing object to stream", exception);
}
});
} catch (Exception exception) {
logger.error("exception occurred while publishing data", exception);
}
logger.info("finished streaming records");
};
return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(responseBody);
}
Service:
public Stream<Data> streamData() {
jdbcTemplate.setFetchSize(500);
String q = "SELECT .....";
return this.jdbcTemplate.queryForStream(q,
(resultSet, rowNum) -> {
Data d = transform(resultSet);
return d;
}
);
}
All seems to be work fine for some time, but after some time of streaming the data, error shows up on server side as:
org.springframework.web.context.request.async.AsyncRequestNotUsableException: Response not usable after async request completion.
On client side I see error as:
Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8080/stream": Premature EOF
I am not able to find out root cause.
Any input on this would be helpful.