標籤:
http://www.actionsky.com/docs/archives/78 2016年4月7日 周文雅
目錄
- 1 起因
- 2 說明
- 3 MySQL調整參數的方式
- 3.1 計算 request_open_files
- 3.1.1 根據配置值計算request_open_files
- 3.1.2 計算effective_open_files
- 3.1.3 修正 request_open_files
- 3.2 計算出生效的參數值
- 3.2.1 修正 open_files_limit
- 3.2.2 修正 max_connections
- 3.2.3 修正table_cache_size
- 4 舉例
起因
非root使用者運行MySQL,當MySQL配置比較高時,MySQL運行中生效的參數值與配置的值不一樣。
這篇文章的目的是為了說明在系統資源不夠的情況下,MySQL 是怎麼調整以下三個參數的: open_files_limit、max_connections、 table_open_cache。
說明
此文涉及到三個參數open_files_limit、 max_connections、 table_open_cache。與這三個參數相關的系統資源是開啟檔案數限制,即檔案描述符(fd)限制。
系統參數與檔案描述符的關係
– max_connection & fd : 每一個MySQL connection都需要一個檔案描述符
– table_open_cache & fd: 開啟一張表至少需要一個檔案描述符,如開啟MyISAM需要兩個fd
– 系統的開啟檔案數限制可以通過 ulimit -n查看
MySQL調整參數的方式
- 根據配置(三個參數的配置值或預設值)計算
request_open_files(需要的檔案描述符)
- 擷取有效系統的限制值
effective_open_files
- 根據
effective_open_files調整request_open_files
- 根據調整後的
request_open_files,計算實際生效的參數值(show variables 可查看參數值)
計算
request_open_files根據配置值計算
request_open_files
request_open_files有三個計算條件
// 最大串連數+同時開啟的表的最大數量+其他(各種日誌等等) limit_1= max_connections + table_cache_size * 2 + 10; //假設平均每個串連開啟的表的數量(2-4) //源碼中是這麼寫的: //We are trying to allocate no less than // max_connections*5 file handles limit_2= max_connections * 5; //mysql 預設的預設是5000 limit_3= open_files_limit ? open_files_limit : 5000;所以open_files_limit期待的最低 request_open_files= max(limit_1, limit_2,limit_3);
計算
effective_open_files
MySQL 的思路:
在有限值的的範圍內MySQL 盡量將effective_open_files的值設大
修正
request_open_files
requested_open_files= min(effective_open_files, request_open_files);
計算出生效的參數值修正
open_files_limit
open_files_limit = effective_open_files
修正
max_connections
max_connections 根據 request_open_files 來做修正。
limit = requested_open_files - 10 - TABLE_OPEN_CACHE_MIN * 2;
- 如果配置的
max_connections值大於limit,則將 max_connections 的值修正為limit
- 其他情況下
max_connections 保留配置值
修正
table_cache_size
table_cache_size 會根據 request_open_files 來做修正
// mysql table_cache_size 最小值,400limit1 = TABLE_OPEN_CACHE_MIN // 根據 requested_open_files 計算limit2 = (requested_open_files - 10 - max_connections) / 2limit = max(limit1,limt2);
- 如果配置的
table_cache_size 值大於limit,則將 table_cache_size 的值修正為limit
- 其他情況下
table_cache_size 保留配置值
舉例
以下用例在非 root 使用者下運行
參數設定://mysql max_connections = 500 table_open_cache = 999//ulimit -n 1500生效的值:open_files_limit = 1500max_connections = min[(1500 - 10 - 800),500] = 500table_open_cache = ( 1500 - 10 - 500) / 2 = 495
在Linux最大開啟檔案數限制下 MySQL 對參數的調整