1. Choose the appropriate storage engine: InnoDB
Unless your data table is used for read-only or full-text search (I believe that when it comes to full-text search, no one will use MYSQL anymore), you should choose InnoDB by default.
When you test it yourself, you may find that MyISAM is faster than InnoDB because: MyISAM only caches indexes, while InnoDB caches data and indexes, and MyISAM does not support transactions. But if you use innodb_flush_log_at_trx_commit = 2 you can get close read performance (a hundredfold difference).
1.1 How to convert an existing MyISAM database to InnoDB:
mysql -u [USER_NAME] -p -e "SHOW TABLES IN [DATABASE_NAME];" | tail -n +2 | xargs -I '{}' echo "ALTER TABLE {} ENGINE=InnoDB;" > alter_table.sqlperl -p -i -e 's/(search_[a-z_]+ ENGINE=)InnoDB//1MyISAM/g' alter_table.sqlmysql -u [USER_NAME] -p [DATABASE_NAME] < alter_table.sql
1.2 Create InnoDB FILE for each table separately:
innodb_file_per_table=1
This ensures that the ibdata1 file does not get too large and out of control. Especially when executing mysqlcheck -o --all-databases.
2. Ensure that the data is read from the memory, and the data is stored in the memory
2.1 Large enough innodb_buffer_pool_size
It is recommended to store the data completely in innodb_buffer_pool_size, that is, plan the capacity of innodb_buffer_pool_size according to the storage amount. This way you can read data entirely from memory, minimizing disk operations.
2.1.1 How to make sure that innodb_buffer_pool_size is large enough that data is read from memory instead of hard disk?
method 1
mysql> SHOW GLOBAL STATUS LIKE 'innodb_buffer_pool_pages_%';+----------------------------------+--------+| Variable_name | Value |+----------------------------------+--------+| Innodb_buffer_pool_pages_data | 129037 || Innodb_buffer_pool_pages_dirty | 362 || Innodb_buffer_pool_pages_flushed | 9998 || Innodb_buffer_pool_pages_free | 0 | !!!!!!!!| Innodb_buffer_pool_pages_misc | 2035 || Innodb_buffer_pool_pages_total | 131072 |+----------------------------------+--------+6 rows in set (0.00 sec)
It is found that Innodb_buffer_pool_pages_free is 0, indicating that the buffer pool has been used up, and innodb_buffer_pool_size needs to be increased
Several other parameters of InnoDB:
innodb_additional_mem_pool_size = 1/200 of buffer_poolinnodb_max_dirty_pages_pct 80%
Method 2
Or use the iostat -d -x -k 1 command to view the operation of the hard disk.
2.1.2 Whether there is enough memory on the server for planning
Execute echo 1 > /proc/sys/vm/drop_caches to clear the file cache of the operating system, and you can see the real memory usage.
2.2 Data warm-up
By default, only a certain piece of data is read once, it will be cached in innodb_buffer_pool. Therefore, the database has just been started, and data warm-up needs to be performed to cache all the data on the disk into memory. Data warm-up can improve read speed.
For InnoDB databases, you can use the following methods to preheat data:
1. Save the following script as MakeSelectQueriesToLoad.sql
SELECT DISTINCT CONCAT('SELECT ',ndxcollist,' FROM ',db,'.',tb, ' ORDER BY ',ndxcollist,';') SelectQueryToLoadCache FROM ( SELECT engine,table_schema db,table_name tb, index_name,GROUP_CONCAT(column_name ORDER BY seq_in_index) ndxcollist FROM ( SELECT B.engine,A.table_schema,A.table_name, A.index_name,A.column_name,A.seq_in_index FROM information_schema.statistics A INNER JOIN ( SELECT engine,table_schema,table_name FROM information_schema.tables WHERE engine='InnoDB' ) B USING (table_schema,table_name) WHERE B.table_schema NOT IN ('information_schema','mysql') ORDER BY table_schema,table_name,index_name,seq_in_index ) A GROUP BY table_schema,table_name,index_name ) AAORDER BY db,tb;
2. 执行
mysql -uroot -AN < /root/MakeSelectQueriesToLoad.sql > /root/SelectQueriesToLoad.sql
3. 每次重启数据库,或者整库备份前需要预热的时候执行:
mysql -uroot < /root/SelectQueriesToLoad.sql > /dev/null 2>&1
2.3 不要让数据存到 SWAP 中
如果是专用 MYSQL 服务器,可以禁用 SWAP,如果是共享服务器,确定 innodb_buffer_pool_size 足够大。或者使用固定的内存空间做缓存,使用 memlock 指令。
3. 定期优化重建数据库
mysqlcheck -o –all-databases 会让 ibdata1 不断增大,真正的优化只有重建数据表结构:
CREATE TABLE mydb.mytablenew LIKE mydb.mytable;INSERT INTO mydb.mytablenew SELECT * FROM mydb.mytable;ALTER TABLE mydb.mytable RENAME mydb.mytablezap;ALTER TABLE mydb.mytablenew RENAME mydb.mytable;DROP TABLE mydb.mytablezap;
4. 减少磁盘写入操作
4.1 使用足够大的写入缓存 innodb_log_file_size
但是需要注意如果用 1G 的 innodb_log_file_size ,假如服务器当机,需要 10 分钟来恢复。
推荐 innodb_log_file_size 设置为 0.25 * innodb_buffer_pool_size
4.2 innodb_flush_log_at_trx_commit
这个选项和写磁盘操作密切相关:
innodb_flush_log_at_trx_commit = 1 则每次修改写入磁盘
innodb_flush_log_at_trx_commit = 0/2 每秒写入磁盘
如果你的应用不涉及很高的安全性 (金融系统),或者基础架构足够安全,或者 事务都很小,都可以用 0 或者 2 来降低磁盘操作。
4.3 避免双写入缓冲
innodb_flush_method=O_DIRECT
5. 提高磁盘读写速度
RAID0 尤其是在使用 EC2 这种虚拟磁盘 (EBS) 的时候,使用软 RAID0 非常重要。
6. 充分使用索引
6.1 查看现有表结构和索引
SHOW CREATE TABLE db1.tb1/G
6.2 添加必要的索引
索引是提高查询速度的唯一方法,比如搜索引擎用的倒排索引是一样的原理。
索引的添加需要根据查询来确定,比如通过慢查询日志或者查询日志,或者通过 EXPLAIN 命令分析查询。
ADD UNIQUE INDEXADD INDEX
6.2.1 比如,优化用户验证表:
添加索引
ALTER TABLE users ADD UNIQUE INDEX username_ndx (username);ALTER TABLE users ADD UNIQUE INDEX username_password_ndx (username,password);
每次重启服务器进行数据预热
echo “select username,password from users;” > /var/lib/mysql/upcache.sql
添加启动脚本到 my.cnf
[mysqld]init-file=/var/lib/mysql/upcache.sql
6.2.2 使用自动加索引的框架或者自动拆分表结构的框架
比如,Rails 这样的框架,会自动添加索引,Drupal 这样的框架会自动拆分表结构。会在你开发的初期指明正确的方向。所以,经验不太丰富的人一开始就追求从 0 开始构建,实际是不好的做法。
7. 分析查询日志和慢查询日志
记录所有查询,这在用 ORM 系统或者生成查询语句的系统很有用。
log=/var/log/mysql.log
注意不要在生产环境用,否则会占满你的磁盘空间。
记录执行时间超过 1 秒的查询:
long_query_time=1log-slow-queries=/var/log/mysql/log-slow-queries.log
8. 激进的方法,使用内存磁盘
现在基础设施的可靠性已经非常高了,比如 EC2 几乎不用担心服务器硬件当机。而且内存实在是便宜,很容易买到几十G内存的服务器,可以用内存磁盘,定期备份到磁盘。
将 MYSQL 目录迁移到 4G 的内存磁盘
mkdir -p /mnt/ramdisksudo mount -t tmpfs -o size=4000M tmpfs /mnt/ramdisk/mv /var/lib/mysql /mnt/ramdisk/mysqlln -s /tmp/ramdisk/mysql /var/lib/mysqlchown mysql:mysql mysql
9. 用 NOSQL 的方式使用 MYSQL
B-TREE 仍然是最高效的索引之一,所有 MYSQL 仍然不会过时。
用 HandlerSocket 跳过 MYSQL 的 SQL 解析层,MYSQL 就真正变成了 NOSQL。
10. 其他
- 单条查询最后增加 LIMIT 1,停止全表扫描。
- 将非”索引”数据分离,比如将大篇文章分离存储,不影响其他自动查询。
- 不用 MYSQL 内置的函数,因为内置函数不会建立查询缓存。
- PHP 的建立连接速度非常快,所有可以不用连接池,否则可能会造成超过连接数。当然不用连接池 PHP 程序也可能将
- 连接数占满比如用了 @ignore_user_abort(TRUE);
- 使用 IP 而不是域名做数据库路径,避免 DNS 解析问题