MySQL中使用流式查詢避免數(shù)據(jù)OOM
一、
程序訪問MySQL數(shù)據(jù)庫時,當查詢出來的數(shù)據(jù)量特別大時,數(shù)據(jù)庫驅(qū)動把加載到的數(shù)據(jù)全部加載到內(nèi)存里,就有可能會導(dǎo)致內(nèi)存溢出(OOM)。
其實在MySQL數(shù)據(jù)庫中提供了流式查詢,允許把符合條件的數(shù)據(jù)分批一部分一部分地加載到內(nèi)存中,可以有效避免OOM;本文主要介紹如何使用流式查詢并對比普通查詢進行性能測試。
二、JDBC實現(xiàn)流式查詢
使用JDBC的PreparedStatement/Statement的setFetchSize方法設(shè)置為Integer.MIN_VALUE或者使用方法Statement.enableStreamingResults()可以實現(xiàn)流式查詢,在執(zhí)行ResultSet.next()方法時,會通過數(shù)據(jù)庫連接一條一條的返回,這樣也不會大量占用客戶端的內(nèi)存。
public int execute(String sql, boolean isStreamQuery) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int count = 0;
try {
//獲取數(shù)據(jù)庫連接
conn = getConnection();
if (isStreamQuery) {
//設(shè)置流式查詢參數(shù)
stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);
} else {
//普通查詢
stmt = conn.prepareStatement(sql);
}
//執(zhí)行查詢獲取結(jié)果
rs = stmt.executeQuery();
//遍歷結(jié)果
while(rs.next()){
System.out.println(rs.getString(1));
count++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(stmt, rs, conn);
}
return count;
}
「PS」:上面的例子中通過參數(shù)isStreamQuery來切換「流式查詢」與「普通查詢」,用于下面做測試對比。
三、性能測試
創(chuàng)建了一張測試表my_test進行測試,總數(shù)據(jù)量為27w條,分別使用以下4個測試用例進行測試:
- 大數(shù)據(jù)量普通查詢(27w條)
- 大數(shù)據(jù)量流式查詢(27w條)
- 小數(shù)據(jù)量普通查詢(10條)
- 小數(shù)據(jù)量流式查詢(10條)
3.1. 測試大數(shù)據(jù)量普通查詢
@Test
public void testCommonBigData() throws SQLException {
String sql = "select * from my_test";
testExecute(sql, false);
}
3.1.1. 查詢耗時
27w 數(shù)據(jù)量用時 38 秒

3.1.2. 內(nèi)存占用情況
使用將近 1G 內(nèi)存

3.2. 測試大數(shù)據(jù)量流式查詢
@Test
public void testStreamBigData() throws SQLException {
String sql = "select * from my_test";
testExecute(sql, true);
}
3.2.1. 查詢耗時
27w 數(shù)據(jù)量用時 37 秒

3.2.2. 內(nèi)存占用情況
由于是分批獲取,所以內(nèi)存在30-270m波動

3.3. 測試小數(shù)據(jù)量普通查詢
@Test
public void testCommonSmallData() throws SQLException {
String sql = "select * from my_test limit 100000, 10";
testExecute(sql, false);
}
3.3.1. 查詢耗時
10 條數(shù)據(jù)量用時 1 秒

3.4. 測試小數(shù)據(jù)量流式查詢
@Test
public void testStreamSmallData() throws SQLException {
String sql = "select * from my_test limit 100000, 10";
testExecute(sql, true);
}
3.4.1. 查詢耗時
10 條數(shù)據(jù)量用時 1 秒

四、總結(jié)
MySQL 流式查詢對于內(nèi)存占用方面的優(yōu)化還是比較明顯的,但是對于查詢速度的影響較小,主要用于解決大數(shù)據(jù)量查詢時的內(nèi)存占用多的場景。
「DEMO地址」:https://github.com/zlt2000/mysql-stream-query
到此這篇關(guān)于MySQL中使用流式查詢避免數(shù)據(jù)OOM的文章就介紹到這了,更多相關(guān)MySQL 流式查詢內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信