I'm working on a Java server with a JSON REST API powered by Jersey and Jackson. The code boils down to something like this:
@GET
@Path("/data")
@ManagedAsync
public void getData(@Suspended final AsyncResponse response) {
Stream<MyDataObject> dataStream = myDataBase.getData();
// How to stream the data to the client
// instead of collecting it in a List first?
List<MyDataObject> data = dataStream.collect(Collectors.toList());
response.resume(Response.ok(data).build());
}
Instead of collecting the data in a List
before sending it to the client, we would like to stream the results to the client since the amount of objects can be huge. From searches on google and stackoverflow I see I probably need StreamingOutput
but I don't know how to connect the Stream via Jackson to Jersey.
In short: How to stream the results from the database directly to the client?