How to close a Stream of a REST Service?

徘徊边缘 提交于 2020-05-15 14:15:38

问题


I need to make a java REST service that will return an inputstream as a response. My problem is that I don't know how to close the stream after the client receives the entire stream. I'm using Java and CXF. Thanks

@GET
@Path("/{uuid}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getAttachmentByUuid(@PathParam("uuid")String uuid)
{
 //getting inputstream from AWS S3
 InpputSream is=getStreamFromS3(uuid);
 return Response.status(Response.Status.OK).entity(is).build();
 // will this "is" stream causes memory leak,, do I have to close it. Client side is not controlled by me
}

回答1:


JAX-RS is implemented using Java servlets. In case of CXF is used CXFServlet. Your stream will be sent to client using the HttpServletResponse of the servlet interface

public void doGet(HttpServletRequest request, HttpServletResponse response)

You should not close an stream source (HttpServletResponse) if you have not created it. It is responsability of the container, and you can interfere with the life cycle of the request

See also Is is necessary to close the input stream returned from HttpServletRequest?




回答2:


If you have a stream to close, consider try with resources:

@GET
@Path("/{uuid}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getAttachmentByUuid(@PathParam("uuid")String uuid)
{
 //getting inputstream from AWS S3
 // the try block opens the stream and guarantees to close it
 try (InputStream is=getStreamFromS3(uuid)) {
     return Response.status(Response.Status.OK).entity(from(is)).build();
 }
}

This requires Java 7 and onwards. It's also awesome!

If you're in Java 6, then you would have to make your own finally block to remember to close the stream for you.




回答3:


You might be looking to use a 'Conduit' See CXF Apache Custom Transport for more info. Be Careful though, the documentation states :

It is strongly recommended to don’t break streaming in Conduit and Destination implementations, if physical protocol supports it. CXF is completely streaming oriented – it causes high performance and scalability.



来源:https://stackoverflow.com/questions/40660219/how-to-close-a-stream-of-a-rest-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!