優化JDBC中讀取大數據字段,提高並發能力
在獲取大數據量文本字段時,如果直接rs.getString(),當同時很多人訪問量,會導致內存占用高,係統響應變慢,因此我們可以采用循環讀取256字節,這樣就大大提高了並發能力。以下是代碼實現
public static String getLargeTextField(ResultSet rs, int columnIndex)
throws SQLException
{
Reader bodyReader = null;
String value = null;
if(isStreamTextRequired()){
bodyReader = rs.getCharacterStream(columnIndex);
if (bodyReader != null)
try {
char buf[] = new char[256];
StringWriter out = new StringWriter(256);
int len;
while ( (len = bodyReader.read(buf)) >= 0)
out.write(buf, 0, len);
value = out.toString();
out.close();
}
catch (Exception e) {
logger.error(e);
throw new SQLException("Failed to load text field");
}
finally {
try {
bodyReader.close();
}
catch (Exception e) {}
}
return value;
}
return rs.getString(columnIndex);
}
最後更新:2017-04-02 05:21:04