Prometheus监控MySQL主从数据库

案例分析Prometheus监控MySQL主从数据库

1. 规划节点

节点规划,见表1。

表1 节点规划

IP主机名节点
192.168.100.3masterPrometheus + Grafana
192.168.100.3mastermysql/master + mysqld_exporter + node_exporter
192.168.100.4nodemysql/master + mysqld_exporter + node_exporter

案例实施

1. 基础环境准备
(1)配置节点时间同步
[root@master ~]# yum install -y chrony
[root@master ~]# systemctl enable chronyd --now
[root@master ~]# vim /etc/chrony.conf
...
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
#server 192.168.100.3 iburst
server ntp1.aliyun.com iburst
server ntp2.aliyun.com iburst
server ntp3.aliyun.com iburst
...
# Allow NTP client access from local network.
#allow 192.168.0.0/16
allow 192.168.100.0/16
...
(2)重启服务
[root@master ~]# systemctl restart chronyd
(3)同步阿里云时间服务器
[root@master ~]# chronyc sources
210 Number of sources = 2
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^- 120.25.115.20                 2   6    25     2  +3773us[+3773us] +/-   26ms
^* 203.107.6.88                  2   6    17    10  +1189us[+4744us] +/-   19ms
[root@master ~]# date
Thu Sep 26 08:39:22 CST 2024
2. 配置MySQL主从
(1)配置 yum 源
[root@master ~]# vim /etc/yum.repos.d/centos.repo 
[centos]
name=centos
baseurl=file:///opt/centos
gpgcheck=0
[k8s]
name=k8s
baseurl=file:///opt/kubernetes-repo
gpgcheck=0
(2)安装 mariadb 服务

master节点安装

[root@master ~]# yum install -y mariadb-server mariadb

启动服务

[root@master ~]# systemctl enable mariadb --now

设置mysql登录密码

[root@master ~]# mysqladmin password 000000

master节点配置 my.cnf 文件

[root@master ~]# vim /etc/my.cnf
[mysqld]
log_bin=mysql-bin
server_id=1
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

重启服务

[root@master ~]# systemctl restart mariadb

node节点安装

[root@node ~]# yum install -y mariadb-server mariadb

启动服务

[root@node ~]# systemctl enable mariadb --now

设置mysql登录密码

[root@node ~]# mysqladmin password 000000

node节点配置 my.cnf 文件

[root@node ~]# vim /etc/my.cnf
[mysqld]
log_bin=mysql-bin
server_id=2
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock

重启服务

[root@node ~]# systemctl restart mariadb
(3)sql语句配置主从

master节点

[root@master ~]# mysql -uroot -p000000
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> grant replication slave on *.* to 'slave'@'%' identified by '000000';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> grant replication slave on *.* to 'slave'@'localhost' identified by '000000';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

node节点

[root@node ~]# mysql -uroot -p000000
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> CHANGE MASTER TO
    -> MASTER_HOST='192.168.100.3',
    -> MASTER_USER='slave',
    -> MASTER_PASSWORD='000000';
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.100.3
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 752
               Relay_Log_File: mariadb-relay-bin.000002
                Relay_Log_Pos: 1036
        Relay_Master_Log_File: mysql-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 752
              Relay_Log_Space: 1332
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
1 row in set (0.01 sec)
3. 编写启动项(方法一)
(1)安装 Prometheus
[root@master ~]# tar -zxvf prometheus-2.37.0.linux-amd64.tar.gz -C /usr/local/
[root@master ~]# mv /usr/local/prometheus-2.37.0.linux-amd64 /usr/local/prometheus
[root@master ~]# cd /usr/lib/systemd/system/
[root@master system]# cat prometheus.service
[Unit]
Description=prometheus

[Service]
ExecStart=/usr/local/prometheus/prometheus --config.file=/usr/local/prometheus/prometheus.yml
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure

[Install]
WantedBy=multi-user.target

重新加载 Systemd 配置文件

[root@master system]# systemctl daemon-reload
[root@master system]# systemctl enable prometheus --now
[root@master system]# netstat -ntpl | grep 9090
(2)安装 Grafana
[root@master ~]# tar -zxvf grafana-enterprise-8.3.6.linux-amd64.tar.gz -C /usr/local/
[root@master ~]# cd /usr/lib/systemd/system/
[root@master system]# cat grafana.service
[Unit]
Description=grafana

[Service]
ExecStart=/usr/local/grafana-8.3.6/bin/grafana-server -homepath=/usr/local/grafana-8.3.6/
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure

[Install]
WantedBy=multi-user.target

重新加载 Systemd 配置文件

[root@master system]# systemctl daemon-reload
[root@master system]# systemctl enable grafana --now
[root@master ~]# netstat -ntpl | grep 3000
(3)安装 Node Exporter
[root@master ~]# scp node_exporter-1.3.1.linux-amd64.tar.gz mysqld_exporter-0.12.1.linux-amd64.tar.gz master:/root/
[root@master ~]# scp node_exporter-1.3.1.linux-amd64.tar.gz mysqld_exporter-0.12.1.linux-amd64.tar.gz node:/root/
[root@master ~]# tar -zxvf node_exporter-1.3.1.linux-amd64.tar.gz -C /usr/local/
[root@master ~]# cd /usr/lib/systemd/system
[root@master system]# cat node_exporter.service
[Unit]
Description=node_exporter

[Service]
ExecStart=/usr/local/node_exporter-1.3.1.linux-amd64/node_exporter
Restart=always

[Install]
WantedBy=multi-user.target

重新加载 Systemd 配置文件

[root@master system]# systemctl daemon-reload
[root@master system]# systemctl enable node_exporter --now
[root@master system]# netstat -ntpl | grep node
(4)编写启动项
[root@master ~]# cd /usr/lib/systemd/system
[root@master system]# cat mysqld_exporter.service
[Unit]
Description=mysqld_exporter

[Service]
ExecStart=/usr/local/mysqld_exporter-0.12.1.linux-amd64/mysqld_exporter --config.my-cnf=/usr/local/mysqld_exporter-0.12.1.linux-amd64/my.cnf
Restart=always

[Install]
WantedBy=multi-user.target

重新加载 Systemd 配置文件

[root@master system]# systemctl daemon-reload
[root@master system]# systemctl enable mysqld_exporter --now
[root@master system]# netstat -ntpl | grep mysqld
4. 二进制启动(方法二)
(1)启动 Prometheus
[root@master ~]# tar -zxvf prometheus-2.37.0.linux-amd64.tar.gz -C /usr/local/
[root@master ~]# cd /usr/local/prometheus-2.37.0.linux-amd64/
[root@master prometheus-2.37.0.linux-amd64]# nohup ./prometheus &  
[root@master prometheus-2.37.0.linux-amd64]# netstat -ntpl | grep 9090
(2)启动 Grafana
[root@master ~]# tar -zxvf grafana-enterprise-8.3.6.linux-amd64.tar.gz -C /usr/local/
[root@master ~]# cd /usr/local/grafana-8.3.6/bin
[root@master bin]# nohup ./grafana-server &  
[root@master bin]# netstat -ntpl | grep 3000
(3)启动 Node Exporter
[root@master ~]# tar -zxvf node_exporter-1.3.1.linux-amd64.tar.gz -C /usr/local/
[root@master ~]# cd /usr/local/node_exporter-1.3.1.linux-amd64/
[root@master node_exporter-1.3.1.linux-amd64]# nohup ./node_exporter &  
[root@master node_exporter-1.3.1.linux-amd64]# netstat -ntpl | grep 9100
(4)安装 mysqld_exporter
[root@master ~]# tar -zvxf mysqld_exporter-0.12.1.linux-amd64.tar.gz -C /usr/local/
[root@master ~]# cd /usr/local/mysqld_exporter-0.12.1.linux-amd64/
[root@master mysqld_exporter-0.14.0.linux-amd64]# cat my.cnf
[client]
user=root
password='123456'
[root@master mysqld_exporter-0.14.0.linux-amd64]# ./mysqld_exporter --config.my-cnf=./my.cnf 
5. 配置 Prometheus 监控
(1)编写监控系统的配置文件
[root@master ~]# cd /usr/local/prometheus/
[root@master prometheus]# cat prometheus.yml
# my global config
global:
  scrape_interval: 5s
  evaluation_interval: 5s

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# Scrape configurations
scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]
  
  - job_name: "mysql-master-slave"
    static_configs:
      - targets: ["192.168.100.3:9104"]
      - targets: ["192.168.100.4:9104"]
        labels:
          instance: mysql-master-slave
  
  - job_name: "nodes"
    static_configs:
      - targets: ["192.168.100.3:9100"]
      - targets: ["192.168.100.4:9100"]
        labels:
          instance: nodes
  - job_name: "grafana"
    static_configs:
      - targets: ["192.168.100.3:3000"]
        labels:
          instance: grafana
(2)重启 Prometheus 后刷新页面
# 启动项方式部署
[root@master system]# systemctl restart prometheus
# 二进制启动
[root@master prometheus-2.37.0.linux-amd64]# netstat -ntpl | grep prometheus
tcp6       0      0 :::9090                 :::*                    LISTEN      128942/./prometheus 
[root@master prometheus-2.37.0.linux-amd64]# pkill -9 prometheus
[root@master prometheus-2.37.0.linux-amd64]# ./prometheus
(3)登录到 Prometheus 控制台查看状态

image-20240926083429748

如果出现报错 out of bounds 删除数据目录

[root@master prometheus-2.37.0.linux-amd64]# ll
total 206628
drwxr-xr-x 2 3434 3434        38 Jul 14  2022 console_libraries
drwxr-xr-x 2 3434 3434       173 Jul 14  2022 consoles
drwxr-xr-x 8 root root       206 Sep 26 07:00 data
-rw-r--r-- 1 3434 3434     11357 Jul 14  2022 LICENSE
-rw------- 1 root root    434968 Sep 25 19:07 nohup.out
-rw-r--r-- 1 3434 3434      3773 Jul 14  2022 NOTICE
-rwxr-xr-x 1 3434 3434 109655433 Jul 14  2022 prometheus
-rw-r--r-- 1 3434 3434      1175 Sep 25 19:11 prometheus.yml
-rwxr-xr-x 1 3434 3434 101469395 Jul 14  2022 promtool
[root@master prometheus-2.37.0.linux-amd64]# rm -rf data/

再次启动 Prometheus

[root@master prometheus-2.37.0.linux-amd64]# ./prometheus
(4)配置 Grafana 监控模版

image-20240926084334861

image-20240926084459228

(5)配置 Grafana Dashboard

image-20240926084715247

(6)查看 MySQL 状态

监控模板7371

image-20240926084814154

(7)查看 Node 状态

监控模版12227

image-20240926093116387

<think>嗯,用户现在问的是关于MySQL主从数据库的最优方法。我需要先确认用户的需求是什么。他们可能是在搭建主从复制,或者优化现有的配置。主从复制常用于读写分离、负载均衡、数据备份或者高可用性。 首先,用户可能是一个开发人员或者系统管理员,想要了解如何设置和优化MySQL主从复制。他们可能已经有一定的数据库基础,但需要更详细的步骤或最佳实践。 接下来,我需要考虑回答的结构。通常,主从复制的步骤包括配置主库和从库,设置复制账户,获取二进制日志位置,配置从库连接主库,启动复制,然后监控和维护。另外,优化部分可能涉及网络、硬件、参数调整、过滤规则、高可用性方案等。 用户可能还关心常见问题,比如数据一致性、延迟问题、故障处理等。是否需要提到GTID(全局事务标识符)?因为GTID可以简化复制管理和故障恢复,但可能在旧版本中不支持。 另外,安全性方面,复制账户的权限设置,SSL加密传输数据,这些都是需要注意的点。可能还需要提到监控工具,比如Percona Toolkit或者内置的SHOW SLAVE STATUS命令。 用户可能没有提到他们的MySQL版本,不同版本的优化方法可能不同,比如MySQL 5.6引入了GTID,而MySQL 8.0有其他改进。需要建议使用较新版本以获得更好的功能和性能。 是否需要分点回答?之前的回答关于Qt下载用了分步骤,这次可能也需要类似的清晰结构,比如配置步骤、优化方法、注意事项、高可用扩展等。 还要考虑用户可能遇到的典型问题,比如主从延迟,这时候可以建议调整sync_binlog,innodb_flush_log_at_trx_commit参数,使用并行复制等。 另外,备份策略也很重要,即使有了主从复制,定期备份仍是必须的。可能需要提到使用mysqldump或者物理备份工具。 最后,是否需要推荐一些工具或资源,比如官方文档、Percona的博客、监控工具等? 总结下来,回答的结构应该是:先介绍主从复制的概念和用途,然后详细步骤,接着优化方法,注意事项,常见问题处理,最后扩展建议。这样用户能逐步了解如何配置和优化。</think>以下是MySQL主从数据库的**最优配置方法及核心实践**,涵盖设计、部署、优化和常见问题解决方案: --- ### 一、主从复制的核心价值 - **读写分离**:主库(Master)处理写操作,从库(Slave)处理读查询。 - **数据冗余**:实时备份主库数据,提升容灾能力。 - **负载均衡**:分散高并发场景下的访问压力。 - **高可用基础**:为后续搭建集群(如MHA、GTID集群)提供支持。 --- ### 二、最优配置步骤 #### 1. **环境准备** - **版本一致性**:主从MySQL版本需兼容(建议主库≥从库,推荐MySQL 5.7+或8.0)。 - **网络优化**:主从服务器间延迟需低(建议内网互通,带宽≥1Gbps)。 #### 2. **主库配置(Master)** ```ini # my.cnf 主库关键配置 [mysqld] server_id = 1 # 唯一ID(从库需不同) log_bin = /var/log/mysql/mysql-bin.log # 启用二进制日志 binlog_format = ROW # 推荐ROW模式确保数据一致性 binlog_do_db = db1,db2 # 指定同步的数据库(可选) ``` - **创建复制账户**: ```sql CREATE USER 'replica'@'%' IDENTIFIED BY 'SecurePass123!'; GRANT REPLICATION SLAVE ON *.* TO 'replica'@'%'; FLUSH PRIVILEGES; ``` #### 3. **从库配置(Slave)** ```ini # my.cnf 从库关键配置 [mysqld] server_id = 2 # 唯一ID relay_log = /var/log/mysql/mysql-relay.log read_only = ON # 从库设为只读(避免误写) ``` #### 4. **启动复制** - **获取主库状态**(主库执行): ```sql SHOW MASTER STATUS; -- 记录File和Position值 ``` - **从库连接主库**(从库执行): ```sql CHANGE MASTER TO MASTER_HOST='192.168.1.100', MASTER_USER='replica', MASTER_PASSWORD='SecurePass123!', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=154; START SLAVE; ``` - **验证状态**: ```sql SHOW SLAVE STATUS\G -- 确保 Slave_IO_Running 和 Slave_SQL_Running 均为 Yes ``` --- ### 三、高级优化策略 #### 1. **降低复制延迟** - **并行复制**(MySQL 5.7+): ```ini slave_parallel_type = LOGICAL_CLOCK slave_parallel_workers = 4 # 根据CPU核数调整 ``` - **半同步复制**(增强数据一致性): ```ini # 主库配置 plugin_load = "rpl_semi_sync_master=semisync_master.so" rpl_semi_sync_master_enabled = 1 # 从库配置 plugin_load = "rpl_semi_sync_slave=semisync_slave.so" rpl_semi_sync_slave_enabled = 1 ``` #### 2. **安全加固** - **SSL加密传输**: ```sql CHANGE MASTER TO MASTER_SSL=1; ``` - **限制复制账户权限**:仅授予`REPLICATION SLAVE`权限。 #### 3. **监控与维护** - **监控指标**: - `Seconds_Behind_Master`(延迟时间) - `Slave_IO_State`(I/O线程状态) - **工具推荐**: - Percona Toolkit:检测数据一致性(`pt-table-checksum`) - Prometheus + Grafana:实时监控集群状态 --- ### 四、常见问题与解决 1. **主从数据不一致** - **修复方法**:使用`mysqldump`重新全量同步,或通过`pt-table-sync`工具修复差异。 2. **复制中断(如主键冲突)** - **临时跳过错误**: ```sql STOP SLAVE; SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; START SLAVE; ``` 3. **主库宕机切换** - **手动切换流程**: 1. 确保所有从库追平日志。 2. 将一个从库提升为新主库(`RESET MASTER;`)。 3. 其他从库重新指向新主库。 --- ### 五、扩展建议 - **GTID模式**(MySQL 5.6+):简化故障恢复,避免依赖`binlog`文件名和位置。 - **多源复制**(MySQL 5.7+):单从库同时复制多个主库。 - **结合中间件**:使用ProxySQL或MaxScale实现自动读写分离。 --- 通过以上方法,可构建高性能、高可靠的MySQL主从架构。实际部署前需充分测试,并根据业务负载调整参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值