Jersey Web服务可伸缩方法,用于下载文件并回复客户端

问题描述 投票:10回答:2

我需要使用Jersey构建一个Web服务,该服务从另一个服务下载一个大文件并返回给客户端。我想让jersey读取一些字节到缓冲区并将这些字节写入客户端套接字。

我希望它使用非阻塞I / O,因此我不会使线程繁忙。 (无法实现)

    @GET
    @Path("mypath")
    public void getFile(final @Suspended AsyncResponse res) {
        Client client = ClientBuilder.newClient();
        WebTarget t = client.target("http://webserviceURL");
        t.request()
            .header("some header", "value for header")
                .async().get(new InvocationCallback<byte[]>(){

            public void completed(byte[] response) {
                res.resume(response);
            }

            public void failed(Throwable throwable) {
                res.resume(throwable.getMessage());
                throwable.printStackTrace();
                //reply with error
            }

        });
    }

到目前为止,我已经有了这段代码,我相信Jersey会下载完整的文件,然后将其写入客户端,这不是我想要的。有什么想法吗?

java web-services jersey scalability nonblocking
2个回答
4
投票

客户端异步请求,不会为您的用例做很多事情。对于“即发即弃”用例而言,它更有意义。但是,您可以做的只是从客户端InputStream获得Response,然后与服务器端StreamingResource混合以流式传输结果。服务器将从其他远程资源传入的数据开始发送。

下面是一个例子。 "/file"端点是提供文件的虚拟远程资源。 "/client"端点将消耗它。

@Path("stream")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public class ClientStreamingResource {

    private static final String INFILE = "Some File";

    @GET
    @Path("file")
    public Response fileEndpoint() {
        final File file = new File(INFILE);
        final StreamingOutput output = new StreamingOutput() {
            @Override
            public void write(OutputStream out) {

                try (FileInputStream in = new FileInputStream(file)) {
                    byte[] buf = new byte[512];
                    int len;
                    while ((len = in.read(buf)) != -1) {
                        out.write(buf, 0, len);
                        out.flush();
                        System.out.println("---- wrote 512 bytes file ----");
                    }
                } catch (IOException ex) {
                    throw new InternalServerErrorException(ex);
                }
            }
        };
        return Response.ok(output)
                .header(HttpHeaders.CONTENT_LENGTH, file.length())
                .build();
    }

    @GET
    @Path("client")
    public void clientEndpoint(@Suspended final AsyncResponse asyncResponse) {
        final Client client = ClientBuilder.newClient();
        final WebTarget target = client.target("http://localhost:8080/stream/file");
        final Response clientResponse = target.request().get();

        final StreamingOutput output = new StreamingOutput() {
            @Override
            public void write(OutputStream out) {
                try (final InputStream entityStream = clientResponse.readEntity(InputStream.class)) {
                    byte[] buf = new byte[512];
                    int len;
                    while ((len = entityStream.read(buf)) != -1) {
                        out.write(buf, 0, len);
                        out.flush();
                        System.out.println("---- wrote 512 bytes client ----");
                    }
                } catch (IOException ex) {
                    throw new InternalServerErrorException(ex);
                }
            }
        };
        ResponseBuilder responseBuilder = Response.ok(output);
        if (clientResponse.getHeaderString("Content-Length") != null) {
            responseBuilder.header("Content-Length", clientResponse.getHeaderString("Content-Length"));
        }
        new Thread(() -> {
            asyncResponse.resume(responseBuilder.build());
        }).start();
    }
}

我使用cURL发出请求,并使用jetty-maven-plugin可以从命令行运行示例。当您运行它并发出请求时,您应该看到服务器日志记录

---- wrote 512 bytes file ----
---- wrote 512 bytes file ----
---- wrote 512 bytes client ----
---- wrote 512 bytes file ----
---- wrote 512 bytes client ----
---- wrote 512 bytes file ----
---- wrote 512 bytes client ----
---- wrote 512 bytes file ----
---- wrote 512 bytes client ----
...

cURL客户端跟踪结果时>

enter image description here

摆脱这一点的原因是,“远程服务器”日志记录与客户端资源的日志记录同时发生。这表明客户端不等待接收整个文件。它开始接收字节后便开始发送字节。

有关示例的一些注意事项:
  • 我使用了非常小的缓冲区大小(512),因为我正在测试一个小的(1Mb)文件。我真的不想等待大型文件进行测试。但是我想大文件应该可以正常工作。当然,您将需要将缓冲区大小增加到更大。

  • 为了使用较小的缓冲区,您需要将Jersey属性ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER设置为0。原因是Jersey保留在内部缓冲区8192中,这将导致我的512字节数据块不刷新,直到缓冲了8192个字节。所以我只是禁用它。

  • 使用ServerProperties.OUTBOUND_CONTENT_LENGTH_BUFFER时,应该像我一样使用另一个线程。您可能要使用执行程序,而不是显式创建线程。如果您不使用其他线程,那么您仍在从容器的线程池中阻止该线程。


  • 更新

    代替管理自己的线程/执行器,您可以用AsyncResponse注释客户端资源,并让Jersey管理线程

    @ManagedAsync

    0
    投票

    谢谢您的解决方案。我想知道您是否找到了通过非阻塞IO解决相同问题的方法?

    © www.soinside.com 2019 - 2024. All rights reserved.