一、前言
程式通路
MySQL
資料庫時,當查詢出來的資料量特别大時,資料庫驅動把加載到的資料全部加載到記憶體裡,就有可能會導緻記憶體溢出(OOM)。
其實在
MySQL
資料庫中提供了流式查詢,允許把符合條件的資料分批一部分一部分地加載到記憶體中,可以有效避免OOM;本文主要介紹如何使用流式查詢并對比普通查詢進行性能測試。
二、JDBC實作流式查詢
使用JDBC的
PreparedStatement/Statement
的
setFetchSize
方法設定為
Integer.MIN_VALUE
或者使用方法
Statement.enableStreamingResults()
可以實作流式查詢,在執行
ResultSet.next()
方法時,會通過資料庫連接配接一條一條的傳回,這樣也不會大量占用用戶端的記憶體。
public int execute(String sql, boolean isStreamQuery) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int count = 0;
try {
//擷取資料庫連接配接
conn = getConnection();
if (isStreamQuery) {
//設定流式查詢參數
stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);
} else {
//普通查詢
stmt = conn.prepareStatement(sql);
}
//執行查詢擷取結果
rs = stmt.executeQuery();
//周遊結果
while(rs.next()){
System.out.println(rs.getString(1));
count++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(stmt, rs, conn);
}
return count;
}
PS:上面的例子中通過參數 isStreamQuery
來切換流式查詢與普通查詢,用于下面做測試對比。
三、性能測試
建立了一張測試表
my_test
進行測試,總資料量為
27w
條,分别使用以下4個測試用例進行測試:
- 大資料量普通查詢(27w條)
- 大資料量流式查詢(27w條)
- 小資料量普通查詢(10條)
- 小資料量流式查詢(10條)
3.1. 測試大資料量普通查詢
@Test
public void testCommonBigData() throws SQLException {
String sql = "select * from my_test";
testExecute(sql, false);
}
3.1.1. 查詢耗時
27w 資料量用時 38 秒
3.1.2. 記憶體占用情況
使用将近 1G 記憶體

3.2. 測試大資料量流式查詢
@Test
public void testStreamBigData() throws SQLException {
String sql = "select * from my_test";
testExecute(sql, true);
}
3.2.1. 查詢耗時
27w 資料量用時 37 秒
3.2.2. 記憶體占用情況
由于是分批擷取,是以記憶體在30-270m波動
3.3. 測試小資料量普通查詢
@Test
public void testCommonSmallData() throws SQLException {
String sql = "select * from my_test limit 100000, 10";
testExecute(sql, false);
}
3.3.1. 查詢耗時
10 條資料量用時 1 秒
3.4. 測試小資料量流式查詢
@Test
public void testStreamSmallData() throws SQLException {
String sql = "select * from my_test limit 100000, 10";
testExecute(sql, true);
}
3.4.1. 查詢耗時
四、總結
MySQL 流式查詢對于記憶體占用方面的優化還是比較明顯的,但是對于查詢速度的影響較小,主要用于解決大資料量查詢時的記憶體占用多的場景。
DEMO位址:
https://github.com/zlt2000/mysql-stream-query掃碼關注有驚喜!