如何在Vert.x(java)中使用Jackson流式传输JSON结果



我正在使用Vert.x为类似Java数据库的服务制作RESTapi。将JSON结果作为字符串写入请求流并不太困难,如下所示:

...
routeMatcher.get("/myservice/api/v1/query/:query", req -> {
    // get query
    String querySring = req.params().get("query");           
    Query query = jsonMapper.readValue(querySring, Query.class);
    // my service creates a list of resulting records...
    List<Record> result = myservice.query(query);                
    String jsonResult = jsonMapper.writeValueAsString(result);
    // write entire string to response
    req.response().headers().set("Content-Type", "application/json; charset=UTF-8");
    req.response().end(jsonResult);    
});
...

然而,我想使用Jackson的方法将Java列表流式传输到请求对象:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(Outputstream, result);

但我不知道如何将Jackson的Outputstream参数连接到Vert.x的re.response(),因为他们有自己的Buffer系统,似乎与Jackson的java.io.Outputstream自变量不兼容。

我不能将杰克逊与Vert.x结合使用吗?我应该用Vert.x自己的JSON库手工编写一个自定义序列化程序吗?其他建议?

我假设您正在生成巨大的JSON文档,因为对于较小的JSON文档来说,字符串输出就足够了:objectMapper.writeValue(<String>, result);

流有问题。ObjectMapper不知道结果大小,您最终会得到一个异常:

java.lang.IllegalStateException: You must set the Content-Length header to be the total size of the message body BEFORE sending any data if you are not using HTTP chunked encoding.
        at org.vertx.java.core.http.impl.DefaultHttpServerResponse.write(DefaultHttpServerResponse.java:474)

因此,在您的示例中,我将使用JSON输出的临时文件,然后将它们刷新为响应(我还没有测试代码)

File tmpFile = File.createTempFile("tmp", ".json");
mapper.writeValue(tmpFile, result);
req.response().sendFile(tmpFile.getAbsolutePath(), (result) -> tmpFile.delete());

如果您最初知道内容长度,您可以使用以下代码将OutputStreamWriteStream 映射

import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.streams.WriteStream;
import java.io.IOException;
import java.io.OutputStream;
public class OutputWriterStream extends OutputStream {
    public WriteStream writeStream;
    public Runnable closeHandler;
    @Override
    public void write(int b) throws IOException {
        throw new UnsupportedOperationException();
    }
    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (off == 0 && len == b.length) {
            writeStream.write(new Buffer(b));
            return;
        }
        byte[] bytes = new byte[len];
        System.arraycopy(b, off, bytes, 0, len);
        writeStream.write(new Buffer(bytes));
    }
    @Override
    public void write(byte[] b) throws IOException {
        writeStream.write(new Buffer(b));
    }
    @Override
    public void close() throws IOException {
        closeHandler.run();
    }
}

这可能会更好一点(并为Vertx3更新)答案:

import io.vertx.core.file.AsyncFile;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.streams.WriteStream;
import java.io.IOException;
import java.io.OutputStream;
public class OutputWriterStream extends OutputStream {
    public OutputWriterStream(final WriteStream response) {
        this.response = response;
        this.buffer = new byte[8192];
    }
    @Override
    public synchronized void write(final int b) throws IOException {
        buffer[counter++] = (byte) b;
        if (counter >= buffer.length) {
            flush();
        }
    }
    @Override
    public void flush() throws IOException {
        super.flush();
        if (counter > 0) {
            byte[] remaining = buffer;
            if (counter < buffer.length) {
                remaining = new byte[counter];
                System.arraycopy(buffer, 0, remaining, 0, counter);
            }
            response.write(Buffer.buffer(remaining));
            counter = 0;
        }
    }
    @Override
    public void close() throws IOException {
        flush();
        super.close();
        if (response instanceof HttpServerResponse) {
            try {
                response.end();
            }
            catch (final IllegalStateException ignore) {
            }
        }
        else if (response instanceof AsyncFile) {
            ((AsyncFile) response).close();
        }
    }
    private final WriteStream<Buffer> response;
    private final byte[] buffer;
    private int counter = 0;
}

相关内容

  • 没有找到相关文章

最新更新