记一次博客服务器的 MySQL 占用内存过高优化记录

一、前言

在阿里云购买了1核2G内存的服务器搭建了博客,但是目前MySQL占用内存达到了惊人的 66%,其他程序占用内存不多,2G内存加上redis,应用程序,基本要占用80%以上的内存,所以,导致博客服务经常会挂掉,需要经常手动重启服务。

由于服务器一天的访问量并不多,并发访问也不高,并不需要把 MySQL 优化的多好,只要能正常运行就够了,加上有 Redis 缓存这一层,几乎很少会跑到 MySQL 查询。

所以综合起来,MySQL 压根不用担心它会挂掉,可以把默认的优化方案修改一下,以便把占用的内存释放出来。

二、查询内存占用

查看内存占用进程:top (然后按下M,注意大写)

file

  • PID:进程 ID
  • %CPU:CPU 占用百分比
  • %MEM:内存占用百分比
  • COMMAND:程序命令名称

可以看到,MySQL进程占了很高的内存,一共2G的内存,总共占了 60%多,所以,需要对MySQL进行调优。

如果发现某个不需要的进程占用了过高的内存或 CPU,可以直接使用 kill <PID> 杀掉进程。

进程杀掉程序就停了,我们不能直接杀掉 MySQL,具体解决思路见下一个步骤。

三、解决思路

MySQL 在启动的时候,会占用一部分的内存来作为缓冲区,这样做的原因是可以优化查询速度,我们可以发现只要查询过一次 MySQL,然后用相同的语句再次查询,第二次查询会比第一次更快,这其中就用到了 MySQL 自身的缓存系统。

MySQL 的缓存机制是当某一个连接访问某张表时,MySQL 会先检查访问的表是否在缓存区中,如果这张表已经在缓存区中打开,那就会直接访问缓存区从而加快查询速度,如果这张表不在缓存区,那就会从实际的数据库文件进行查询,然后再把这张表加入缓存区,以便后续查询加快速度。

由于这个机制我们的 MySQL 在运行过程占用的内存会逐渐增加,1G 的内存不适合用来做 MySQL 的优化,我们要做的就是去掉 MySQL 用来加快查询的各种机制。

四、解决方案

修改 MySQL 配置文件 my.cnf,找到 [mysqld] 下添加如下内容:

查询默认参数:

show VARIABLES like '%table_open_cache%'

show VARIABLES like '%table_definition_cache%'

show VARIABLES like '%performance_schema_max_table_instances%'

file

进入到博客服务器:

root@iZ: cd /etc/mysql
root@iZ:/etc/mysql# vi my.cnf

需要修改的参数:

[mysqld]
// 此处省略其他配置,添加如下内容
table_open_cache=200
table_definition_cache=400
performance_schema_max_table_instances=400
performance_schema=off

修改完之后,重启MySQL:

root@iZ:/etc/mysql# service mysql restart

保存然后重启 MySQL,OK!内存已经降到 10%一下了。

file

查看阿里云服务器监控:
file

可以看到内存瞬间降低了很多 , 起到了立竿见影的效果^_^

各个配置项的具体用途:
file

通过调整前面 3 个配置项的值,占用内存均有 1~3% 程度的降低,罪魁祸首便是 performance_schema,将其设置为 off 之后,内存直接降低了 20%!

其详细介绍可参考 MySQL 官方文档: MySQL Performance Schema

当然除了上面几个配置项之外,MySQL 仍有许多可以优化的配置项,但是现在既然已经实现了自己的目的,就暂时不进行扩展阅读了,以后如果需要更深入的优化,到时候再学也不迟(日均 IP 100+ 根本不用考虑什么优化嘛~)。

五、附录

my.cnf 文件

root@iZ94j7ehy5oZ:/etc/mysql# pwd      
/etc/mysql
root@iZ94j7ehy5oZ:/etc/mysql# cat my.cnf           
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address       = 127.0.0.1
#
# * Fine Tuning
#
key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit   = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries   = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id      = 1
#log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size         = 100M
innodb_large_prefix = ON
innodb_file_format = BARRACUDA
max_connections = 10000
#binlog_do_db       = include_database_name
#binlog_ignore_db   = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem
# [20210923-add] 
table_open_cache=200
table_definition_cache=400
performance_schema_max_table_instances=400
performance_schema=off

[mysqldump]
quick
quote-names
max_allowed_packet  = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completition

[isamchk]
key_buffer      = 16M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

相关文章:
MySQL占用内存过高优化记录

为者常成,行者常至