MySQL之thread cache


  最近突然對MySQL的連接非常感興趣,從status根據thread關鍵字可以查出如下是個狀態

show global status like 'thread%';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| Threads_cached    | 57    |
| Threads_connected | 1268  |
| Threads_created   | 31715 |
| Threads_running   | 1     |
+-------------------+-------+

Thread_cached:The number of threads in the thread cache

Thread_connected:The number of currently open connections.

Thread_created:The number of threads created to handle connections.

Thread_running:The number of threads that are not sleeping.

 

  以上是這4個狀態的含義,thread_connected等於show processlist,thread_running代表真正在運行的(等於1一般就是這個show status命令本身),thread_cached代表mysql管理的線程池中還有多少可以被復用的資源,thread_created代表新創建的thread(根據官方文檔,如果thread_created增大迅速,需要適當調高thread_cache_size)。

  我們先來實際看下這4個狀態之間的直觀關系。

  從上面這個圖,我們可以總結出來一個公式:running和其他三個狀態關系不大,但肯定不會超過thread_connected

  (new_con-old_con)=create+(old_cache-new_cache)

  從上面公式可以看出,如果create等於0,那么thread_connected減少的和thread_cached增加的相等,thread_connected增加的和thread_cached減少的相等。(其實這也就是thread_cached存在的意義,資源可以復用)

 

  我們來看眼影響thread_cached的參數thread_cache_size

How many threads the server should cache for reuse. When a client disconnects, the client's threads are put in the cache if there are fewer than thread_cache_size threads there. Requests for threads are satisfied by reusing threads taken from the cache if possible, and only when the cache is empty is a new thread created. This variable can be increased to improve performance if you have a lot of new connections. Normally, this does not provide a notable performance improvement if you have a good thread implementation. However, if your server sees hundreds of connections per second you should normally set thread_cache_size high enough so that most new connections use cached threads. By examining the difference between the Connections and Threads_created status variables, you can see how efficient the thread cache is. For details, see Section 5.1.6, “Server Status Variables”.

  眾所周知,mysql建立連接非常消耗資源,所以就有了thread_cache,當已有連接不再使用之后,mysql server不是直接斷開連接,而是將已有連接轉入到thread_cache中,以便下次在有create thread的需求時,可以在cache中復用,提高性能,降低資源消耗。  

  當然,如果已經有了中間件或者其他的連接池管理,那么這個參數就沒有那么重要了,但是如果沒有其他的連接池管理,那么優化這個參數還是可以得到不錯的回報的。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM