AWS AURORA  CPU 100% 的解決方案

  最近作了一個系統,是從各個地方按照不一樣的接口同步訂單,底層採用的是Spring JdbcTempalte,支持按預訂時間分表存儲和查詢的功能,使用到了jdbc的BatchUpdate功能.生產環境採用的是AWS,使用的數據庫方案是AWS的RDS(Rational DataBase Service),這是我第一次使用RDS.本地環境測試起來一切正常,可是發佈到生產環境CPU就飆到100%,且一條直線橫到底.html

 雖然RDS的服務不會掛,可是系統的性能受到嚴重的影響.第一次使用AWS的RDS數據庫,我簡答的認爲Amazon Aurora與經常使用的mysql是同樣的,後來查詢RDS的文檔,才發現有一些不一樣.mysql

Amazon Aurora 是一個兼容 MySQL 的關係數據庫引擎,結合了高端商用數據庫的速度和可用性以及開源數據庫的簡單性和成本效益。Amazon Aurora 的性能最高可達到 MySQL 的五倍,而且能以十分之一的成本提供商用數據庫的安全性、可用性和可靠性。sql

這是http://aws.amazon.com/cn/rds/aurora/上對Aurora的介紹,一直把全部的文檔看完,可是仍是沒有能解決個人問題,經過查詢的ShowProcessList和程序的日誌上來看,發現系統在執行一些Sql方面有嚴重的性能問題.數據庫

好比根據訂單號刪除訂單的同步任務.安全

delete from res_id_list_for_fetch  where ersp='XXX' And source='yyyy'併發

這條語句竟然會死鎖,執行SQL時,若是指定了主鍵,那麼速度是最快的,主鍵是惟一的,因此只需鎖定這一行記錄便可,可是上面的SQL裏面,是有3kw的數據量的基礎上執行的,並且沒有索引,因此直接鎖定了整個表,在40個線程併發執行的狀況下,出現死鎖就不足爲奇了.因此解決方案也是很簡單,對ersp和source創建索引.性能

同時,在執行BatchUpdate時,slowlog的日誌也顯示有性能問題,在stackoverflow 上看到有位仁兄也遇到過這樣的問題測試

http://stackoverflow.com/questions/2993251/jdbc-batch-insert-performance fetch

根據上面的解決方案,在jdbc的url上加入參數url

?useServerPrepStmts=false&rewriteBatchedStatements=true"

默認的狀況下,rewriteBatchedStatements是false,這個參數的設置的解釋以下

I'd like to expand on Bertil's answer, as I've been experimenting with the connection URL parameters.

rewriteBatchedStatements=true is the important parameter. useServerPrepStmts is already false by default, and even changing it to true doesn't make much difference in terms of batch insert performance.

Now I think is the time to write how rewriteBatchedStatements=true improves the performance so dramatically. It does so by rewriting of prepared statements for INSERT into multi-value inserts when executeBatch() (Source). That means that instead of sending the following n INSERT statements to the mysql server each time executeBatch() is called :

INSERT INTO X VALUES (A1,B1,C1)
INSERT INTO X VALUES (A2,B2,C2)
...
INSERT INTO X VALUES (An,Bn,Cn)

It would send a single INSERT statement :

INSERT INTO X VALUES (A1,B1,C1),(A2,B2,C2),...,(An,Bn,Cn)

You can observe it by toggling on the mysql logging (by SET global general_log = 1) which would log into a file each statement sent to the mysql server.

按照以上的解決方案,該創建索引的創建索引,鏈接參數也修改了,部署到生產環境,後來觀察,cup一直穩定在3%.問題獲得解決.

總結 對於常常使用的查詢字段,該創建索引的仍是要創建索性,血的教訓. 

相關文章
相關標籤/搜索