从NIO HTTP下载到Restlet ServerResource响应的管道数据

时间:2012-10-14 13:15:15

标签: restlet

我有一个ServerResource,它通过发送二进制数据来响应GET请求。问题是二进制数据的来源将通过单独的REST调用异步下载(可能通过HttpAsyncClient)。是否可以创建一个表示,我可以在从异步下载到达时提供数据?我需要能够在不阻塞任何线程的情况下完成它,因此需要某种NIO解决方案。

我怀疑我可以使用WriteableRepresetation执行此操作,但我不确定文档的说明方式

  

为此,您只需要创建一个子类并覆盖抽象的Representation.write(WritableByteChannel)方法。当需要实际表示的内容时,连接器将稍后调用此方法。

暗示在调用该方法时,所有内容必须已经可用。

我正在使用v2.1。

2 个答案:

答案 0 :(得分:1)

稍微玩了一下后,看起来可以使用ReadableRepresentation。我不知道是否有更好的方法来创建ReadableByteChannel而不是使用Pipe,但这是我看到的唯一方式,而不必实现我自己的频道。

private static final byte[] HELLO_WORLD = "hello world\n".getBytes(Charsets.UTF_8);

public static class HelloWorldResource extends ServerResource {
    @Get
    public Representation represent() throws Exception {
        final Pipe pipe = Pipe.open();

        // this simulates another process generating the data
        Thread t = new Thread(new Runnable() {
            private final ByteBuffer buf = ByteBuffer.allocate(1);
            private final Pipe.SinkChannel sink = pipe.sink();

            private int offset = 0;

            @Override
            public void run() {
                while (offset < HELLO_WORLD.length) {
                    try {
                        buf.clear();
                        buf.put(HELLO_WORLD[offset++]);
                        buf.flip();

                        while (buf.hasRemaining()) {
                            sink.write(buf);
                        }

                        Thread.sleep(500);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                try {
                    sink.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        t.setDaemon(true);
        t.start();

        return new ReadableRepresentation(pipe.source(), MediaType.TEXT_PLAIN);
    }
}

public static class HelloWorldApplication extends Application {
    @Override
    public synchronized Restlet createInboundRoot() {
        Router router = new Router(getContext());
        router.attach("/hello", HelloWorldResource.class);

        return router;
    }
}

public static void main(String[] args) throws Exception {
    Component component = new Component();
    component.getDefaultHost().attach("", new HelloWorldApplication());

    Server server = component.getServers().add(Protocol.HTTP, 8090);

    component.start();
}

答案 1 :(得分:0)

在使用上述解决方案后,我发现你可以像这样创建一个ReadableByteChannel:

        ByteArrayInputStream stream = new ByteArrayInputStream(myByteArray);
        ReadableByteChannel channel = Channels.newChannel(stream);

上面的答案很好,给我带来了很多麻烦。