简体   繁体   中英

How to efficiently handle MySQL connections with PHP

I'm running an app that interacts with a mysql database using the native Mysql PDO, I'm not using laravel or any framework. So most of the APIs logic is to fetch from DB and/or to insert.

when running on production I can see high memory usage from mysql tasks, check below:

htop 命令的输出

I have a couple of questions.

  1. Is such high memory usage normal? and what's the best practice to manage a proper PHP-MysQL connection in a multi-threaded production-level app?
  2. When an intensive query is running (fetching historical data to plot a graph), the CPU usage jumps to 100% until the query execution finishes it returns back to 2-3%. But during that time the system is completely paused.

I'm thinking of hardware based solutions, such as separating the db server from the app server (currently they both run on the same node) And managing a cluster and using read-only nodes.

But i'd like to know if there are other options, and what's the most efficient way to handle PHP-MySQL connections.

You could also check the query written if there are fully optimized, and connection are closed when not used.

Also you can reduce the load on the mysql server by balancing some work to php.

Also take a look at your query_cache_size, innodb_io_capacity, innodb_buffer_pool_size and max_connection setting in your my.cnf.

Also sometimes upgrading php and doing some caching on your apache can help reduce of ram uses.

https://phoenixnap.com/kb/improve-mysql-performance-tuning-optimization

Normally, innodb_buffer_pool_size is set to about 70% of available RAM, and MySQL will consume that, plus other space that it needs. Scratch that; you have only 1GB of RAM? The buffer_pool needs to be a smaller percentage. It seems that the current value is pretty good.

You top show only 37.2% of RAM in used by MySQL -- the many threads are sharing the same memory.

Sort by memory (in top , use < or > ). Something else is consuming a bunch of RAM.

query_cache_size should be zero.

max_connections should be, say, 10 or 20.

CPU -- You have only one core? So a big query hogging the CPU is to be expected. It also says that I/O was not an issue. You could show us the query, plus SHOW CREATE TABLE and EXPLAIN SELECT... ; perhaps we can suggest how to speed it up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM