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ù)量普通查詢@Testpublic 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)存
@Testpublic 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波動
@Testpublic void testCommonSmallData() throws SQLException { String sql = 'select * from my_test limit 100000, 10'; testExecute(sql, false);}
3.3.1. 查詢耗時
10 條數(shù)據(jù)量用時 1 秒
@Testpublic void testStreamSmallData() throws SQLException { String sql = 'select * from my_test limit 100000, 10'; testExecute(sql, true);}
3.4.1. 查詢耗時
10 條數(shù)據(jù)量用時 1 秒
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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 應(yīng)用經(jīng)驗:關(guān)于IBM DB2數(shù)據(jù)庫的注意事項2. 關(guān)于MySQL的ORDER BY排序詳解3. 基于mybatis batch實現(xiàn)批量提交大量數(shù)據(jù)4. 快速掌握重啟Oracle數(shù)據(jù)庫的操作步驟5. sql server注冊表操作相關(guān)的幾個未公開過程6. 傳 Oracle 欲 收購金蝶?7. VS自帶的SQL server修改密碼并連接使用8. 數(shù)據(jù)庫Oracle9i的企業(yè)管理器簡介9. sQlite常用語句以及sQlite developer的使用與注冊10. SQL server 危險存儲過程刪除與恢復(fù)
