通过Spring JDBC流式传输数据,未知长度 [英] Streaming Data through Spring JDBC, unknown length
问题描述
我目前有一个应用程序通过使用Spring JDBC [SqlLobValue]将byte []插入到我们的数据库中。问题是,这不是一种可扩展的数据接收方式,因为服务器在写入数据库之前缓冲内存中的所有数据。我想从HttpServletRequest Inputstream流式传输数据,但是我可以找到任何以Inputstream作为参数的类的构造函数也需要内容长度作为参数。在将数据发布到我的应用程序时,我不会,也不会要求用户知道内容长度。有没有解决这个限制的方法?
I currently have an application that inserts byte[] into our DB through the use of Spring JDBC [SqlLobValue]. The problem is, this is not a scalable way to take in data, as the server is buffering all the data in memory before writing to the database. I would like to stream the data from the HttpServletRequest Inputstream, but all the constructors I can find for any classes that take an Inputstream as an argument also require the content length as an argument. I do not, and will not, require the user to know the content length when POSTing data to my application. Is there a way around this limitation?
我找不到关于如果我为内容长度传递-1会发生什么的文档,但我的猜测是它会抛出异常。我不确定为什么他们不能让流继续读取,直到read(...)返回-1,这是InputStream的必需行为。
I can find no documentation about what happens if I pass -1 for content length, but my guess is it will throw an Exception. I'm not sure why they couldn't just have the stream keep reading until the read(...) returns -1, the required behavior of an InputStream.
推荐答案
我认为你的意思是InputStream而不是OutputStream。我尝试了这个,但是我的JDBC驱动程序遇到了更大的问题,所以我不确定这是否真的有效。
I presume you meant "InputStream" rather than "OutputStream". I tried this out, but I was having bigger problems with my JDBC driver, so I am unsure if this actually works.
InputStream inputStream = httpServletRequest.getInputStream();
int contentLength = -1; // fake, will be ignored anyway
SqlLobValue sqlLobValue = new SqlLobValue(
inputStream,
contentLength,
new DefaultLobHandler() {
public LobCreator getLobCreator() {
return new DefaultLobHandler.DefaultLobCreator() {
public void setBlobAsBinaryStream(PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength) throws SQLException {
// The contentLength parameter should be the -1 we provided earlier.
// You now have direct access to the PreparedStatement.
// Simply avoid calling setBinaryStream(int, InputStream, int)
// in favor of setBinaryStream(int, InputStream).
ps.setBinaryStream(paramIndex, binaryStream);
}
};
}
}
);
jdbcTemplate.update(
"INSERT INTO foo (bar) VALUES (?)",
new Object[]{ sqlLobValue }
);
这篇关于通过Spring JDBC流式传输数据,未知长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!