Linux(CentOS 8)生产环境部署:MySQL 8.0性能优化与监控方案2024

云信安装大师
90
AI 质量分
11 5 月, 2025
7 分钟阅读
0 阅读

Linux(CentOS 8)生产环境部署:MySQL 8.0性能优化与监控方案2024

引言

在当今数据驱动的时代,MySQL作为最流行的开源关系型数据库之一,在生产环境中的性能表现直接影响着业务系统的稳定性与用户体验。本文将详细介绍在CentOS 8系统上部署MySQL 8.0并进行性能优化与监控的完整方案。

准备工作

环境要求

  • CentOS 8操作系统(建议最小化安装)
  • 至少4GB内存(生产环境推荐16GB以上)
  • 50GB以上磁盘空间(根据数据量调整)
  • root或sudo权限

前置知识

  • 基本的Linux命令行操作
  • MySQL基础概念理解

一、MySQL 8.0安装与基础配置

1.1 添加MySQL官方YUM仓库

代码片段
# 下载MySQL YUM仓库
sudo dnf install -y https://dev.mysql.com/get/mysql80-community-release-el8-4.noarch.rpm

# 验证仓库是否添加成功
sudo dnf repolist enabled | grep "mysql.*-community.*"

1.2 安装MySQL服务器

代码片段
# 安装MySQL服务器
sudo dnf install -y mysql-community-server

# 启动MySQL服务并设置开机自启
sudo systemctl enable --now mysqld

# 检查服务状态
sudo systemctl status mysqld

1.3 安全初始化

代码片段
# 获取临时密码
sudo grep 'temporary password' /var/log/mysqld.log

# 运行安全脚本
sudo mysql_secure_installation

按照提示操作:
1. 输入临时密码
2. 设置新密码(建议包含大小写字母、数字和特殊字符)
3. 移除匿名用户(Y)
4. 禁止root远程登录(Y)
5. 移除测试数据库(Y)
6. 重新加载权限表(Y)

1.4 MySQL配置文件优化 (my.cnf)

编辑配置文件 /etc/my.cnf

代码片段
[mysqld]
# Basic Settings
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

# Character Set Settings
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci

# InnoDB Settings (核心优化)
innodb_buffer_pool_size=12G    # (建议为总内存的50-70%)
innodb_buffer_pool_instances=8 # (每个实例至少1GB)
innodb_log_file_size=2G        # (较大的日志文件提高写入性能)
innodb_flush_method=O_DIRECT   # (减少双缓冲开销)
innodb_flush_log_at_trx_commit=2 # (平衡性能与持久性,生产环境可设为1)
innodb_read_io_threads=16      # (根据CPU核心数调整)
innodb_write_io_threads=16     # (根据CPU核心数调整)

# Connection Settings (连接数优化)
max_connections=1000           # (根据应用需求调整)
thread_cache_size=100          # (减少线程创建开销)

# Query Cache Settings (查询缓存已弃用,保持禁用)
query_cache_type=0             
query_cache_size=0             

# Other Performance Settings
table_open_cache=4000          # (减少表打开操作) 
tmp_table_size=256M            # (提高临时表处理能力)
max_heap_table_size=256M       # (内存表大小限制)

[client]
default-character-set=utf8mb4

[mysql]
default-character-set=utf8mb4

修改后重启MySQL服务:

代码片段
sudo systemctl restart mysqld

二、MySQL性能优化实践

2.1 InnoDB缓冲池调优

代码片段
-- InnoDB缓冲池命中率检查 (>95%为佳)
SELECT 
    CONCAT(ROUND(100*(SELECT variable_value FROM performance_schema.global_status WHERE variable_name = 'Innodb_buffer_pool_read_requests')/
    ((SELECT variable_value FROM performance_schema.global_status WHERE variable_name = 'Innodb_buffer_pool_read_requests') + 
    (SELECT variable_value FROM performance_schema.global_status WHERE variable_name = 'Innodb_buffer_pool_reads')),2),'%') AS hit_rate;

-- InnoDB缓冲池使用情况监控  
SELECT 
    ROUND((data_size + index_size) / POWER(1024,3),2) AS total_data_gb,
    ROUND(buffer_pool_size / POWER(1024,3),2) AS buffer_pool_gb,
    ROUND(((data_size + index_size) / buffer_pool_size)*100,2) AS percent_in_memory,
    ROUND((buffer_pool_size - free_buffers)/POWER(1024,3),2) AS used_memory_gb,
    ROUND(free_buffers/POWER(1024,3),2) AS free_memory_gb,
    ROUND((buffer_pool_size - free_buffers)/buffer_pool_size*100,2) AS buffer_pool_full_percent 
FROM (
    SELECT 
        SUM(data_length+index_length) data_size,
        SUM(index_length) index_size,
        @@innodb_buffer_pool_size buffer_pool_size,
        @@innodb_buffer_pool_chunk_size * @@innodb_buffer_pool_instances * ((@@innodb_buffer_pool_size)/(@@innodb_buffer_pool_chunk_size * @@innodb_buffer_pool_instances)-FLOOR((@@innodb_buffer_pool_size)/(@@innodb_buffer_pool_chunk_size * @@innodb_buffer_pool_instances))) free_buffers 
    FROM information_schema.tables WHERE engine='InnoDB'
) t;

2.2 SQL查询优化分析

代码片段
-- 启用慢查询日志(记录执行超过2秒的查询)
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
SET GLOBAL log_output = 'FILE';

-- MySQL Workbench或命令行查看慢查询日志位置:
SHOW VARIABLES LIKE '%slow_query_log%';

-- EXPLAIN分析慢查询示例:
EXPLAIN SELECT * FROM large_table WHERE user_id = '12345';

-- SQL语句性能分析工具:
SET profiling = ON;
-- [执行你的SQL语句]
SHOW PROFILE;
SHOW PROFILES;

2.3 MySQL索引优化策略

代码片段
-- 查找未使用索引的表和索引:
SELECT 
    object_schema, object_name, index_name 
FROM 
    performance_schema.table_io_waits_summary_by_index_usage 
WHERE 
    index_name IS NOT NULL AND count_star = 0;

-- Redundant Indexes检查:
SELECT 
    s.indexed_table,
    s.indexed_column,
    GROUP_CONCAT(s.index_name ORDER BY seq_in_index) as indexes_on_column,
    COUNT(*) as num_indexes_on_column,
    GROUP_CONCAT(i.non_unique ORDER BY seq_in_index) as uniqueness_of_indexes,
    GROUP_CONCAT(i.sub_part ORDER BY seq_in_index) as subparts_of_indexes_on_column  
FROM (
    SELECT 
        table_schema as indexed_db, table_name as indexed_table, index_name, column_name as indexed_column, seq_in_index  
    FROM information_schema.statistics  
    WHERE table_schema NOT IN ('mysql','information_schema','performance_schema','sys')
) s  
JOIN information_schema.statistics i ON s.indexed_db = i.table_schema AND s.indexed_table = i.table_name AND s.index_name = i.index_name  
GROUP BY indexed_db, indexed_table, indexed_column  
HAVING COUNT(*) >1;

三、MySQL监控方案实施

3.1 Prometheus + Grafana监控体系搭建

3.1.1 Prometheus安装配置:

“`bash

Prometheus安装包下载(最新版请访问官网获取链接)

wget https://github.com/prometheus/prometheus/releases/download/v2.47.0/prometheus-2.47.0.linux-amd64.tar.gz -P /tmp/
tar xvf /tmp/prometheus-.tar.gz -C /opt/
ln -s /opt/prometheus-
/prometheus /usr/local/bin/

Prometheus用户创建和目录准备:

useradd –no-create-home –shell /bin/false prometheus
mkdir -p /etc/prometheus /var/lib/prometheus/data/{metrics,rules}
chown prometheus:prometheus /etc/prometheus /var/lib/prometheus/data/{metrics,rules}

Prometheus配置文件/etc/prometheus/prometheus.yml示例:

global:
scrapeinterval: 15s # Set the scrape interval to every15 seconds.
evaluation
interval:15s # Evaluate rules every15 seconds.
scrapeconfigs:
– job
name: ‘prometheus’
staticconfigs:
– targets: [‘localhost:9090’]
– job
name: ‘mysql’
staticconfigs:
– targets: [‘localhost:9104’] # mysqld
exporter默认端口9104

Systemd服务配置/etc/systemd/system/prometheus.service:

[Unit]
Description=Prometheus Monitoring System and Time Series Database.
Documentation=https://prometheus.io/docs/introduction/overview/

[Service]
User=prometheus
Group=prometheus
Type=simple
ExecStart=/usr/local/bin/prometheus \
–config.file=/etc/prometheus/prometheus.yml \
–storage.tsdb.path=/var/lib/prometheus/data/metrics \
–web.external-url=http://yourserverip:9090 \
–web.enable-lifecycle \
–storage.tsdb.max-block-duration=12h

Restart=always

[Install]
WantedBy=multi-user.target

systemctl daemon-reload && systemctl enable prometheusservice && systemctl start prometheusservice && systemctl status prometheusservice

firewall-cmd –add-port={9090/tcp} –permanent && firewall-cmd –reload && firewall-cmd –list-all | grep port

curl http://localhost:9090/graph

3 .1 .2 MySQL Exporter部署:

wget https://github.com/promet heus/mysqldexporter/releases/download/v*.X.X/mysqldexporter-X.X.X.linux-amd64.tar.gz

tar xvfz mysqldexporter-X.X.X.linux-amd64.tar.gz && mv mysqldexporter-X.X.X.linux-amd64/mysqld_exporter/usr/local/bin/

useradd –no-create-home –shell/bin/false mysql_exporter

mkdir/etc/mysqlexporter && chown mysqlexporter/etc/mysql_exporter/

cat>/etc/.my.cnf<

cat>/etc/systemd/system/mysqldexporter.service<exporter Group-mysqlexporter [Service] Type-simple Restart-always ExecStart=/usr/local/bin/mys ql d _ex porter \ — config.my-cnf “/etc/.my.cnf” \ — collect.globalstatus \ — collect.info schema.processlist \ — collect.info schema.queryresponsetime \ — collect.info schema.userstats \ — collect.info schema.tablestats \ — collect.perf schema.eventswaits \ — collect.perf schema.file events \ — collect.perf schema.indexiowaits \ — collect.perf schema.tableiowaits \ — collect.perf schema.tablelockwaits [Install] WantedBy-multi-user.target EOF

systemctl daemon-reload&&systemctl enable mys ql d _ex porter&&systemctl start mys ql d _ex porter&&systemctl status mys ql d _ex porter

firewall-cmd— add-port={9104/tcp}— permanent&&firewall-cmd— reload&&firewall-cmd— list-all|grep port

curl http://localhost :9104/metrics|head-n20 ###3 .1 .3 Grafana安装配置: sudo yum install-y https://dl.grafana.com/oss/release/grafana-X.X.X.x86_64.rpm sudo systemctlenable grafana-server&&sudo systemctl start grafana-server&&sudo systemctl status grafana-server

firewall-cmd— add-port={3000/tcp}— permanent&&firewall-cmd— reload&&firewall-cmd— list-all|grep port

访问http://yourserverip :3000默认用户名admin/admin首次登录后修改密码 Data Sources→Add data source→Prometh eus URL填写http://localhost :9090 Save&Test确认连接成功 Dashboard→Import→输入7362(M ySQL Overview模板ID)→Load选择Prometh eus数据源→Import即可获得专业监控面板 ##四、备份与灾难恢复策略 ###4 .1物理备份方案:xtrabackup ###安装Percona XtraBackup: sudo yum install-y https://repo.percona.com/yum/percona-release-latest.noarch.rpm sudo percona-release enable-only tools release sudo yum install-y percona-xtrabackup-X X ###全量备份示例: innobackupex— user=— password=— no-timestamp/backups/fullbackupdate+%Y%m%d ###增量备份示例: innobackupex— user=— password=— incremental/backups/incrementalbackupdate+%Y%m%d— incremental-basedir=/backups/fullbackupdate+%Y%m%d ###恢复流程: innobackupex— apply-log-only/backups/base innobackupex— apply-log-only/backups/base\ — incremental-dir=/backups/incremental innobackupex— copy-back/backups/base ###自动化脚本示例: !/bin/bash BACKUPDIR=”/backups/mysql” DATE=$(date +%Y%m%d-%H%M%S) LOGFILE=”/var/log/mysqlbackup.log” RETENTION=”7″ echo”[$(date)] Starting backup”>>$LOGFILE innobackupex\ — user=”backupuser”\ — password=”YourPassword”\ — no-timestamp\ $BACKUPDIR/full-$DATE>>$LOGFILE if[$?-eq];then echo”[$(date)] Full backup completed successfully”>>$LOGFILE find$BACKUPDIR-name’full-mtime+$RETENTION-delete find$BACKUP_DIR-name’incremental-mtime+$RETENTION-delete else echo”[$(date)] Backup failed!”>>$LOGFILE exit fi ##五、安全加固措施 ###5 .1网络层安全配置 firewall-cmd— permanent\ — add-rich-rule=’rule family=”ipv source address=”192 .168 . port protocol=”tcp”port=”3306 accept’ firewall-cmd— reload ###5 .2数据库用户权限最小化原则 CREATE USER’appuser@’192 .168.% IDENTIFIED BY’ComplexPassword’; GRANT SELECT INSERT UPDATE DELETE ON appdb.*TO’appuser@’192 .168.%’; FLUSH PRIVILEGES; ###5 .3定期审计配置 SET GLOBAL auditlogformat=’JSON’; SET GLOBAL auditlogfile=’/var/log/mysql-audit.log’; SET GLOBAL auditlogpolicy=’ALL’; ##总结本文详细介绍了在CentOS生产环境下部署MySQL并进行性能优化的完整方案包括:基础安装配置核心参数调优SQL查询优化索引策略专业监控体系搭建以及备份恢复和安全加固等关键环节通过实施这些措施可以显著提升数据库性能和稳定性建议读者根据实际业务需求调整参数值并定期审查系统状态

原创 高质量