Jersey - 从 ResultSet 返回流
我有一个带有 CLOB 字段的表(MySQL MediumText)。
我想将输入流返回到该 CLOB。 我的资源代码如下所示:
@GET
public StreamingOutput getAsStream(int id) {
try {
// prepare the statement object
ResultSet rs = stmt.executeQuery();
if (rs.next()) return new StreamingOutput() {
public void write(OutputStream outputStream) throws ... {
copy(rs.getBinaryStream(1), outputStream);
}
}
}
finally {
rs.close();
stmt.close();
connection.close();
}
}
这看起来不对。在 Jersey 有机会将流写入响应之前,代码会关闭数据库资源(结果集、语句和连接)。
我可以在 StreamingOutput.write 方法中关闭数据库资源。但它也感觉不对 - 我让一些外部容器关闭我的资源。
我能想到的最后一个想法是将整个流读入内存然后发送。我当然不想这么做。
那么,有人有更好的主意吗?
我检查了 使用 Java Jersey 返回文件,这没有多大帮助。
谢谢, 多伦
I have a table with a CLOB field (MySQL MediumText).
I want to return an input stream to that CLOB.
My resource code looks like this:
@GET
public StreamingOutput getAsStream(int id) {
try {
// prepare the statement object
ResultSet rs = stmt.executeQuery();
if (rs.next()) return new StreamingOutput() {
public void write(OutputStream outputStream) throws ... {
copy(rs.getBinaryStream(1), outputStream);
}
}
}
finally {
rs.close();
stmt.close();
connection.close();
}
}
Which doesn't look right. The code closes the db resources (resultset, statement and connection) before Jersey has a chance to write the stream to the response.
I can close the db resources in the StreamingOutput.write
method. But it also does not feel right - I'm letting some outside container close my resources.
The last idea I can think of is to read the entire stream into memory and then send it. I don't want to do it of course.
So, anyone got any better idea?
I checked Return a file using Java Jersey which didn't help much.
Thanks,
Doron
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您显示的代码将无法工作。您在方法中创建了一个匿名内部类,然后将其作为返回对象传递给容器。新类中的写入对象实际上不会被调用,直到您的方法完成后的某个时间,当然,此时您已经关闭了所有连接。
从概念上讲,尝试直接从数据库进行流传输可能不是一个好主意。您不希望在客户端决定消耗输入流的时间内保持连接打开状态。最好的办法是将数据读入内存,然后将该数据传输到客户端。
Yes, your code as shown will not work. You created an anonymous inner class in your method and then handed it as the return object to the container. The write object in the new class doesn't actually get invoked until sometime after your method has already completed, at which time of course you have already closed up all your connections.
Conceptually, trying to stream directly from the database is probably not a good idea. You don't want to hold open a connection for the amount of time the client decides to take in consuming the input stream. The best thing to do is read the data into memory, and then stream that data to the client.