MySQL主從復制與讀寫分離概述

前言:

????????在數據驅動的現代應用中,數據庫面臨高并發讀寫與海量存儲的雙重挑戰。單一數據庫實例在性能、可用性及擴展性上逐漸成為瓶頸。MySQL主從復制(Master-Slave Replication)與讀寫分離(Read/Write Splitting)通過分布式架構,將寫操作集中于主庫(Master),讀操作分發至多個從庫(Slave),輔以基于二進制日志(Binlog)的異步/半同步數據同步機制,實現了數據冗余、負載分流與故障快速恢復。這一架構不僅成為企業級數據庫高可用的基石,更為業務提供了彈性擴展的底層支撐。

目錄

一、概述

二、基礎環境設置

????????網絡對時

????????防火墻與SELinux三、配置主從復制

????????主服務配置

????????從服務器配置

????????配置從服務器的所屬主服務器?

????????開啟同步?

????????驗證

主從復制常見問題

四、maxscale概述

五、讀寫分離

1、環境說明

2、mysql主從復制配置

3、maxscale安裝

4、配置maxscale

1.測試數據同步

(1) 在 主服務器 上操作:

(2) 在 從服務器 上驗證同步:

2.測試讀寫分離(通過MaxScale)

3.故障切換測試

(1) 模擬主庫故障:

(2) 檢查MaxScale狀態:

(3) 驗證新主庫寫入:

(4) 恢復舊主庫并檢查同步:

關鍵命令總結

總結


一、概述

1、master開啟二進制日志記錄

2、slave開啟IO進程,從master中讀取二進制日志并寫入slave的中繼日志

3、slave開啟SQL進程,從中繼日志中讀取二進制日志并進行重放

4、最終,達到slave與master中數據一致的狀態,我們稱作為主從復制的過程。

二、基礎環境設置

網絡對時

主與從主機都需要操作

?[root@ryan ~]# cat /etc/chrony.conf | grep -Ev '^$|#'?server ntp.aliyun.com iburst   ###添加或者修改driftfile /var/lib/chrony/driftmakestep 1.0 3rtcsynckeyfile /etc/chrony.keysleapsectz right/UTClogdir /var/log/chrony 
###切換到主
[root@master ~]# timedatectl set-timezone Asia/Shanghai
[root@master mysql]# vim /etc/chrony.conf

[root@master mysql]# systemctl restart chronyd.service 
[root@master mysql]# date
2025年 07月 06日 星期日 17:25:50 CST
###切換到從
[root@slave ~]# timedatectl set-timezone Asia/Shanghai
[root@slave ~]# vim /etc/chrony.conf 

[root@slave ~]# systemctl restart chronyd.service 
[root@slave ~]# date
2025年 07月 06日 星期日 17:29:59 CST

防火墻與SELinux

主與從主機都需要操作

###主
[root@master ~]# systemctl disable --now firewalld
[root@master ~]# setenforce 0
[root@master ~]# getenforce
Permissive###從
[root@slave ~]# systemctl disable --now firewalld
[root@slave ~]# setenforce 0
[root@slave ~]# getenforce
Permissive

三、配置主從復制

主服務配置

?##修改配置文件[root@localhost ~]# cat /etc/my.cnf?## This group is read both both by the client and the server# use it for options that affect everything#[mysqld]log-bin=mysql-binbinlog_format="statement"server-id=11log-slave-updates=true[client-server]?## include all files from the config directory#!includedir /etc/my.cnf.d?##啟動服務[root@localhost ~]# systemctl enable --now mysqld#驗證配置[root@localhost ~]# cd /var/lib/mysql/[root@localhost mysql]# lsauto.cnf ? ? ?  client-cert.pem ? ?  ibdata1 ? ? ? ? ?  mysql-bin.000003 ? mysql_upgrade_info ? server-key.pembinlog.000001 ? client-key.pem ? ? ? ibtmp1 ? ? ? ? ? ? mysql-bin.000004 ? mysqlx.sock ? ? ? ?  sysbinlog.000002 ? db1 ? ? ? ? ? ? ? ? '#innodb_redo' ? ?  mysql-bin.000005 ? mysqlx.sock.lock ? ? undo_001binlog.index ?  db2 ? ? ? ? ? ? ? ? '#innodb_temp' ? ?  mysql-bin.index ?  performance_schema ? undo_002c2407 ? ? ? ? ?'#ib_16384_0.dblwr' ? mysql ? ? ? ? ? ?  mysql.ibd ? ? ? ?  private_key.pemca-key.pem ? ? '#ib_16384_1.dblwr' ? mysql-bin.000001 ? mysql.sock ? ? ? ? public_key.pemca.pem ? ? ? ?  ib_buffer_pool ? ? ? mysql-bin.000002 ? mysql.sock.lock ?  server-cert.pem??##創建從主機可以進行訪問的用戶mysql> create user slave@'192.168.72.%' identified by '123.com';?mysql> grant all on *.* to 'slave'@'192.168.72.%';###密碼插件修改ALTER USER 'slave'@'192.168.166.%' IDENTIFIED WITH mysql_native_password BY '123.com';###查看master正在使用的日志文件及日志書寫位置[root@localhost mysql]# mysqlmysql> show master status;+-------------------+----------+--------------+------------------+| File ? ? ? ? ? ?  | Position | Binlog_Do_DB | Binlog_Ignore_DB |+-------------------+----------+--------------+------------------+| master-bin.000003 | ? ? ?542 | ? ? ? ? ? ?  | ? ? ? ? ? ? ? ?  |+-------------------+----------+--------------+------------------+1 row in set (0.00 sec)#注意:查看位置完畢后,不要對master做insert、update、delete、create、drop等操作!!!

[root@master ~]# systemctl restart mysqld

從服務器配置

?##修改配置文件[root@localhost ~]# cat /etc/my.cnfrelay-log-index=slave-bin.indexserver-id=22##啟動服務[root@localhost ~]# systemctl enable --now mysqld?##配置驗證,此時沒有與主服務器進行連接,所以沒有產生對應的relay log[root@localhost mysql]# lsaria_log.00000001  aria_log_control  ibdata1  ib_logfile0  ib_logfile1  mysql  mysql.sock  performance_schema  test##配置從服務器的所屬主服務器[root@localhost mysql]# mysqlmysql> change master to master_host='192.168.158.4',master_user='slave',master_password='123.com',master_log_file='master-bin.000001',master_log_pos=619;?##啟動slave角色,默認沒有配置主從時,所有的mysql節點都是mastermysql> start slave;##查看slave狀態信息mysql> show slave status\G;*************************** 1. row ***************************Slave_IO_State: Waiting for source to send eventMaster_Host: 192.168.166.230Master_User: slaveMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000005Read_Master_Log_Pos: 2567Relay_Log_File: slave-bin.000004Relay_Log_Pos: 1679Relay_Master_Log_File: mysql-bin.000005Slave_IO_Running: YesSlave_SQL_Running: YesReplicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0Last_Error: Skip_Counter: 0Exec_Master_Log_Pos: 2567Relay_Log_Space: 2416Until_Condition: NoneUntil_Log_File: Until_Log_Pos: 0Master_SSL_Allowed: NoMaster_SSL_CA_File: Master_SSL_CA_Path: Master_SSL_Cert: Master_SSL_Cipher: Master_SSL_Key: Seconds_Behind_Master: 0Master_SSL_Verify_Server_Cert: NoLast_IO_Errno: 0Last_IO_Error: Last_SQL_Errno: 0Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 11Master_UUID: 25105bd5-6fd8-11ef-9dae-000c299fb683Master_Info_File: mysql.slave_master_infoSQL_Delay: 0SQL_Remaining_Delay: NULLSlave_SQL_Running_State: Replica has read all relay log; waiting for more updatesMaster_Retry_Count: 86400Master_Bind: Last_IO_Error_Timestamp: Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: Executed_Gtid_Set: Auto_Position: 0Replicate_Rewrite_DB: Channel_Name: Master_TLS_Version: Master_public_key_path: Get_master_public_key: 0Network_Namespace: 1 row in set, 1 warning (0.00 sec)??#查看數據目錄[root@localhost mysql]# lsaria_log.00000001  ibdata1 ? ?  ib_logfile1  mysql ? ? ? performance_schema  slave-bin.000001  slave-bin.indexaria_log_control ? ib_logfile0  master.info  mysql.sock  relay-log.info ? ?  slave-bin.000002  test
[root@slave ~]# vim /etc/my.cnf.d/mysql-server.cnf 

[root@slave mysql]# systemctl restart mysqld

配置從服務器的所屬主服務器?

?

開啟同步?

mysql> SHOW SLAVE STATUS\G;
*************************** 1. row ***************************Slave_IO_State: Waiting for source to send eventMaster_Host: 192.168.72.155Master_User: slaveMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000010Read_Master_Log_Pos: 589Relay_Log_File: slave-relay-bin.000014Relay_Log_Pos: 326Relay_Master_Log_File: mysql-bin.000010Slave_IO_Running: YesSlave_SQL_Running: YesReplicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0Last_Error: Skip_Counter: 0Exec_Master_Log_Pos: 589Relay_Log_Space: 885Until_Condition: NoneUntil_Log_File: Until_Log_Pos: 0Master_SSL_Allowed: NoMaster_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: NoLast_IO_Errno: 0Last_IO_Error: Last_SQL_Errno: 0Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 11Master_UUID: a0e533b0-51d8-11f0-a49f-000c2939f194Master_Info_File: mysql.slave_master_infoSQL_Delay: 0SQL_Remaining_Delay: NULLSlave_SQL_Running_State: Replica has read all relay log; waiting for more updatesMaster_Retry_Count: 86400Master_Bind: Last_IO_Error_Timestamp: Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: Executed_Gtid_Set: Auto_Position: 0Replicate_Rewrite_DB: Channel_Name: Master_TLS_Version: Master_public_key_path: Get_master_public_key: 0Network_Namespace: 
1 row in set, 1 warning (0.00 sec)ERROR: 
No query specified

驗證

從查看不到任何庫

切換到主創建新庫

?切換到從查看到主新創建的庫

從查看二進制日志主創建指令是否同步

[root@slave ~]# cd /var/lib/mysql
[root@slave mysql]# lsauto.cnf        ca.pem              '#innodb_temp'        public_key.pembinlog.000001   client-cert.pem      mysql                server-cert.pembinlog.000002   client-key.pem       mysql.ibd            server-key.pembinlog.000003   gooddays             mysql.sock           slave-bin.indexbinlog.000004  '#ib_16384_0.dblwr'   mysql.sock.lock      slave-relay-bin.000001binlog.000005  '#ib_16384_1.dblwr'   mysql_upgrade_info   slave-relay-bin.000002binlog.000006   ib_buffer_pool       mysqlx.sock          sysbinlog.000007   ibdata1              mysqlx.sock.lock     undo_001binlog.index    ibtmp1               performance_schema   undo_002ca-key.pem     '#innodb_redo'        private_key.pem
[root@slave mysql]# mysqlbinlog slave-relay-bin.000002

主從復制常見問題

異常:

?mysql> show slave status\G;*************************** 1. row ***************************Slave_IO_State: Connecting to sourceMaster_Host: 192.168.166.230Master_User: slaveMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000005Read_Master_Log_Pos: 2567Relay_Log_File: slave-bin.000004Relay_Log_Pos: 1679Relay_Master_Log_File: mysql-bin.000005Slave_IO_Running: ConnectingSlave_SQL_Running: YesReplicate_Do_DB: Replicate_Ignore_DB: Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0Last_Error: Skip_Counter: 0Exec_Master_Log_Pos: 2567Relay_Log_Space: 2416Until_Condition: NoneUntil_Log_File: Until_Log_Pos: 0Master_SSL_Allowed: NoMaster_SSL_CA_File: Master_SSL_CA_Path: Master_SSL_Cert: Master_SSL_Cipher: Master_SSL_Key: Seconds_Behind_Master: NULLMaster_SSL_Verify_Server_Cert: NoLast_IO_Errno: 2003Last_IO_Error: Error connecting to source 'slave@192.168.166.230:3306'. This was attempt 1/86400, with a delay of 60 seconds between attempts. Message: Can't connect to MySQL server on '192.168.166.230:3306' (113)Last_SQL_Errno: 0Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 11Master_UUID: 25105bd5-6fd8-11ef-9dae-000c299fb683Master_Info_File: mysql.slave_master_infoSQL_Delay: 0SQL_Remaining_Delay: NULLSlave_SQL_Running_State: Replica has read all relay log; waiting for more updatesMaster_Retry_Count: 86400Master_Bind: Last_IO_Error_Timestamp: 240913 04:04:49Last_SQL_Error_Timestamp: Master_SSL_Crl: Master_SSL_Crlpath: Retrieved_Gtid_Set: Executed_Gtid_Set: Auto_Position: 0Replicate_Rewrite_DB: Channel_Name: Master_TLS_Version: Master_public_key_path: Get_master_public_key: 0Network_Namespace: 1 row in set, 1 warning (0.00 sec)

一般情況下,都與網絡通信異常有關系。排查防火墻、物理網絡連接等。二進制日志文件名或位置錯誤也會引起IO線程異常。

?reset replica;##用于重置SQL線程對relay log的重放記錄!!

四、maxscale概述

MaxScale是maridb開發的一個mysql數據中間件,其配置簡單,能夠實現讀寫分離,并且可以根據主從狀態實現寫庫的自動切換。 官網:https://mariadb.com/kb/en/mariadb-enterprise/mariadb-maxscale-20/

下載地址:https://dlm.mariadb.com/3927179/MaxScale/24.02.3/rhel/9/x86_64/maxscale-24.02.3-1.rhel.9.x86_64.rpm

https://dlm.mariadb.com/3993858/MaxScale/24.02.4/rhel/8/x86_64/maxscale-24.02.4-1.rhel.8.x86_64.rpm

五、讀寫分離

1、環境說明

數據庫角色IP應用與系統版本
master192.168.166.25rocky linux9.4 mysql-8.0.36
slave192.168.166.26rocky linux9.4 mysql-8.0.36
slave2192.168.166.27rocky linux9.4 mysql-8.0.36
maxscale192.168.166.9rocky linux9.4 maxscale24.02.3-GA

主帶從

主服務器 (Master): server1 (192.168.72.155:3366)

從服務器 (Slave): server2 (192.168.72.129:3366)

maxscale 192.168.72.9

2、mysql主從復制配置

分別在主從三臺服務器上安裝mysql8,并配置主從復制。

?##由于認證插件問題,需要在master服務器使用下述命令進行更改密碼的驗證插件。ALTER USER'slave'@'%' IDENTIFIED WITH mysql_native_password BY 'password';FLUSH PRIVILEGES;?###修改認證插件##my.cnfdefault-authentication-plugin=mysql_native_password

主配置

[root@master mysql]# vim /etc/my.cnf.d/mysql-server.cnf 

[root@master mysql]# systemctl restart mysqld

從配置

[root@master slave]# vim /etc/my.cnf.d/mysql-server.cnf 

[root@master slave]# systemctl restart mysqld

從查看同步狀態是否正常

3、maxscale安裝

?#下載yum源[root@maxscale ~]# curl -LsS https://r.mariadb.com/downloads/mariadb_repo_setup | sudo bash?# [info] Checking for script prerequisites.?# [info] MariaDB Server version 11.2 is valid?# [info] Repository file successfully written to /etc/yum.repos.d/mariadb.repo?# [info] Adding trusted package signing keys...?/etc/pki/rpm-gpg ~~?# [info] Successfully added trusted package signing keys?# [info] Cleaning package cache...?25 files removed[root@maxscale ~]# ls /etc/yum.repos.d/mariadb.repo ?rocky-addons.repo ?rocky-devel.repo ?rocky-extras.repo ?rocky.repo#安裝maxscale[root@maxscale ~]# yum -y install maxscale

rpm安裝

拖入maxscale軟件包

直接解決依賴下載

[root@maxscale ~]# rpm -ivh maxscale-24.02.3-1.rhel.9.x86_64.rpm 
警告:maxscale-24.02.3-1.rhel.9.x86_64.rpm: 頭V4 RSA/SHA512 Signature, 密鑰 ID e3c94f49: NOKEY
錯誤:依賴檢測失敗:libmicrohttpd.so.12()(64bit) 被 maxscale-24.02.3-1.rhel.9.x86_64 需要libodbc.so.2()(64bit) 被 maxscale-24.02.3-1.rhel.9.x86_64 需要librdkafka++.so.1()(64bit) 被 maxscale-24.02.3-1.rhel.9.x86_64 需要librdkafka.so.1()(64bit) 被 maxscale-24.02.3-1.rhel.9.x86_64 需要nodejs >= 10.0.0 被 maxscale-24.02.3-1.rhel.9.x86_64 需要
[root@maxscale ~]# ls
公共  視頻  文檔  音樂  anaconda-ks.cfg                       nohup.out
模板  圖片  下載  桌面  maxscale-24.02.3-1.rhel.9.x86_64.rpm
[root@maxscale ~]# yum localinstall -y maxscale-24.02.3-1.rhel.9.x86_64.rpm

4、配置maxscale

登錄到主庫

?[root@master ~]# mysql -urootmysql: [Warning] Using a password on the command line interface can be insecure.Welcome to the MySQL monitor. ?Commands end with ; or \g.Your MySQL connection id is 14Server version: 8.0.36 MySQL Community Server - GPL?Copyright (c) 2000, 2023, Oracle and/or its affiliates.?Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.?Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.#創建maxscale用戶密碼是maxscalemysql> CREATE USER 'maxscale'@'%' IDENTIFIED BY 'maxscale';Query OK, 0 rows affected (0.00 sec)#授權maxscale可以查詢所有數據庫mysql> GRANT SELECT ON mysql.* TO 'maxscale'@'%';Query OK, 0 rows affected (0.01 sec)#授權可以看所有數據庫mysql> GRANT SHOW DATABASES ON *.* TO 'maxscale'@'%';Query OK, 0 rows affected (0.00 sec)#創建admin用戶可以在maxscale上登錄mysql> CREATE USER 'admin'@'192.168.166.%' IDENTIFIED BY 'admin';Query OK, 0 rows affected (0.01 sec)

?主創建賬戶

?從打開二進制日志查看主創建用戶指令

[root@slave ~]# cd -
/var/lib/mysql
[root@slave mysql]# lsauto.cnf        ca.pem               mysql                server-key.pembinlog.000001   client-cert.pem      mysql.ibd            slave-bin.indexbinlog.000002   client-key.pem       mysql.sock           slave-relay-bin.000004binlog.000003   gooddays             mysql.sock.lock      slave-relay-bin.000005binlog.000004  '#ib_16384_0.dblwr'   mysql_upgrade_info   slave-relay-bin.000006binlog.000005  '#ib_16384_1.dblwr'   mysqlx.sock          sysbinlog.000006   ib_buffer_pool       mysqlx.sock.lock     undo_001binlog.000007   ibdata1              performance_schema   undo_002binlog.000008   ibtmp1               private_key.pembinlog.index   '#innodb_redo'        public_key.pemca-key.pem     '#innodb_temp'        server-cert.pem
[root@slave mysql]# mysqlbinlog slave-relay-bin.000006

從打開數據庫查看主是否完成數據同步?

?切換到主給maxcale賦予所有權限

切換到從進行驗證權限是否賦予成功

?切換到主創建admin賬戶

切換到從進行驗證

在maxscale上安裝mysql

?[root@maxscale ~]# yum -y install mysql[root@maxscale ~]# which mysql/usr/bin/mysql#登錄到master[root@maxscale ~]# mysql -uadmin -padmin -h192.168.166.25mysql: [Warning] Using a password on the command line interface can be insecure.Welcome to the MySQL monitor. ?Commands end with ; or \g.Your MySQL connection id is 15Server version: 8.0.36 MySQL Community Server - GPL?Copyright (c) 2000, 2023, Oracle and/or its affiliates.?Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.?Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.###因為沒有權限所以只能看到兩個數據庫mysql> show databases;+--------------------+| Database ? ? ? ? ? |+--------------------+| information_schema || performance_schema |+--------------------+2 rows in set (0.00 sec)?mysql> exitBye

回到master主庫設置增刪改查權限

?mysql> GRANT CREATE, SELECT, INSERT, UPDATE, DELETE ON *.* TO 'admin'@'192.168.72.%';Query OK, 0 rows affected (0.00 sec)

在master主庫上授權真機有增刪改查權限

?mysql> CREATE USER 'admin'@'192.168.166.%' IDENTIFIED BY 'admin';Query OK, 0 rows affected (0.01 sec)?mysql> GRANT CREATE, SELECT, INSERT, UPDATE, DELETE ON *.* TO 'admin'@'192.168.72.%';Query OK, 0 rows affected (0.01 sec)

此時再切回到maxscale主機上可以看到所有庫

在maxscale上修改配置文件

?[root@maxscale ~]# vim /etc/maxscale.cnf#先看有無這個[maxscale]threads=auto?#修改后端服務器地址[server1]type=serveraddress=192.168.166.25port=3306protocol=MySQLBackend?[server2]type=serveraddress=192.168.166.26port=3306protocol=MySQLBackend?[server3]type=serveraddress=192.168.166.27port=3306protocol=MySQLBackend?#配置監控[MySQL-Monitor]type=monitormodule=mariadbmonservers=server1,server2,server3user=monitorpassword=monitormonitor_interval=2s?#注釋掉只讀配置#[Read-Only-Service]#type=service#router=readconnroute#servers=server2#user=maxscale#password=maxscale#router_options=slave?#修改讀寫分離服務[Read-Write-Service]type=servicerouter=readwritesplitservers=server1,server2,server3user=maxscalepassword=maxscaleversion_string = 8.0#配置listener#注釋掉只讀#[Read-Only-Listener]#type=listener#service=Read-Only-Service#protocol=mariadbprotocol#port=4008#修改讀寫分離[Read-Write-Listener]type=listenerservice=Read-Write-Serviceprotocol=mariadbprotocolport=3306 #(偽裝成數據庫端口3306)
[root@maxscale maxscale]# cat /etc/maxscale.cnf
#####################################################
# MaxScale documentation:                           #
# https://mariadb.com/kb/en/mariadb-maxscale-24-02/ #
############################################################################################################################################################
# Global parameters                                                                                   #
#                                                                                                     #
# Complete list of configuration options:                                                             #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-mariadb-maxscale-configuration-guide/ #
#######################################################################################################
[maxscale]
threads=auto############################################################################
# Server definitions                                                       #
#                                                                          #
# Set the address of the server to the network address of a MariaDB server.#
############################################################################[server1]
type=server
address=192.168.72.155
port=3306
protocol=MySQLBackend[server2]
type=server
address=192.168.72.129
port=3306
protocol=MySQLBackend
##################################################################################
# Uncomment this and add MaxScale's IP to proxy_protocol_networks in MariaDB for #
# easier user management: https://mariadb.com/kb/en/proxy-protocol-support/      #
##################################################################################
# proxy_protocol=true##################################################################################################
# Monitor for the servers                                                                        #
#                                                                                                #
# This will keep MaxScale aware of the state of the servers.                                     #
# MariaDB Monitor documentation:                                                                 #
# https://mariadb.com/kb/en/maxscale-24-02monitors/                                              #
#                                                                                                #
# The GRANTs needed by the monitor user depend on the actual monitor.                            #
# The GRANTs required by the MariaDB Monitor can be found here:                                  #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-mariadb-monitor/#required-grants #
##################################################################################################[MySQL-Monitor]
type=monitor
module=mariadbmon
servers=server1,server2
user=monitor
password=monitor
monitor_interval=2s
##################################################################################################################
# Uncomment these to enable automatic node failover:                                                             #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-mariadb-monitor/#cluster-manipulation-operations #
#                                                                                                                #
# The GRANTs required for automatic node failover can be found here:                                             #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-mariadb-monitor/#cluster-manipulation-grants     #
##################################################################################################################
# auto_failover=true
# auto_rejoin=true
# enforce_simple_topology=true
# replication_user=<username used for replication>
# replication_password=<password used for replication>
#########################################################################################################
# Uncomment this if you use more than one MaxScale with automatic node failover:                        #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-mariadb-monitor/#cooperative-monitoring #
#########################################################################################################
# cooperative_monitoring_locks=majority_of_all#########################################################################################################
# Service definitions                                                                                   #
#                                                                                                       #
# Service Definition for a read-only service and a read/write splitting service.                        #
#                                                                                                       #
# The GRANTs needed by the service user can be found here:                                              #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-authentication-modules/#required-grants #
#########################################################################################################################################################################################
# ReadConnRoute documentation:                                                 #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-readconnroute/ #
#################################################################################[Read-Only-Service]
#type=service
#router=readconnroute
#servers=server1
#user=service_user
#password=service_pw
#router_options=slave#################################################################################
# ReadWriteSplit documentation:                                                 #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-readwritesplit/ #
#################################################################################
[Read-Write-Service]
type=service
router=readwritesplit
servers=server1,server2
user=maxscale
password=maxscale
version_string = 8.0
####################################################################################################
# Uncomment these to enable transparent transaction replay on node failure:                        #
# https://mariadb.com/kb/en/mariadb-maxscale-2402-maxscale-2402-readwritesplit/#transaction_replay #
####################################################################################################
# transaction_replay=true
# transaction_replay_timeout=30s####################################################################
# Listener definitions for the services                            #
#                                                                  #
# These listeners represent the ports the services will listen on. #
#####################################################################[Read-Only-Listener]
#type=listener
#service=Read-Only-Service
#port=4008
[Read-Write-Listener]
type=listener
service=Read-Write-Service
protocol=mariadbprotocol
port=3306

切換到maxcale做備份并修改配置文件

[root@maxscale ~]# mv /etc/maxscale.cnf /opt/maxscale.cnf.bak [root@maxscale ~]# ls -l /etc/maxscale.cnf
-rw-r--r--. 1 root root 779  7月  6 19:51 /etc/maxscale.cnf
[root@maxscale ~]# ls -l /etc/maxscale.cnf.d/ -d
drwxr-xr-x. 2 maxscale maxscale 6  9月  7  2024 /etc/maxscale.cnf.d/
[root@maxscale ~]# chown maxscale.maxscale /etc/maxscale.cnf[root@maxscale ~]# vim /etc/maxscale.cnf

切換到主庫創建monitor監控用戶

?mysql> CREATE USER 'monitor'@'%' IDENTIFIED BY 'monitor';Query OK, 0 rows affected (0.01 sec)#再添加授權mysql> GRANT REPLICATION CLIENT on *.* to 'monitor'@'%';Query OK, 0 rows affected (0.00 sec)?mysql> GRANT REPLICATION SLAVE on *.* to 'monitor'@'%';Query OK, 0 rows affected (0.01 sec)?mysql> GRANT SUPER,RELOAD on *.* to 'monitor'@'%';Query OK, 0 rows affected, 1 warning (0.01 sec)

啟動服務

[root@maxscale ~]# systemctl start maxscale[root@maxscale maxscale]# systemctl status maxscale
● maxscale.service - MariaDB MaxScale Database ProxyLoaded: loaded (/usr/lib/systemd/system/maxscale.service; enabled; preset: >Active: active (running) since Sun 2025-07-06 20:15:20 CST; 5min agoProcess: 18138 ExecStartPre=/usr/bin/install -d /var/cache/maxscale -o maxsc>Process: 18139 ExecStart=/usr/bin/maxscale (code=exited, status=0/SUCCESS)Main PID: 18141 (maxscale)Tasks: 12 (limit: 22799)Memory: 8.0MCPU: 287msCGroup: /system.slice/maxscale.service└─18141 /usr/bin/maxscale7月 06 20:15:17 maxscale systemd[1]: Starting MariaDB MaxScale Database Proxy...
7月 06 20:15:17 maxscale maxscale[18141]: Module 'mariadbmon' loaded from '/usr/>
7月 06 20:15:17 maxscale maxscale[18141]: Module 'readwritesplit' loaded from '/>
lines 1-15...skipping...
● maxscale.service - MariaDB MaxScale Database ProxyLoaded: loaded (/usr/lib/systemd/system/maxscale.service; enabled; preset: disabled)Active: active (running) since Sun 2025-07-06 20:15:20 CST; 5min agoProcess: 18138 ExecStartPre=/usr/bin/install -d /var/cache/maxscale -o maxscale -g maxscale (code=exited, status=0/SUCCESS)Process: 18139 ExecStart=/usr/bin/maxscale (code=exited, status=0/SUCCESS)Main PID: 18141 (maxscale)Tasks: 12 (limit: 22799)Memory: 8.0MCPU: 287msCGroup: /system.slice/maxscale.service└─18141 /usr/bin/maxscale7月 06 20:15:17 maxscale systemd[1]: Starting MariaDB MaxScale Database Proxy...
7月 06 20:15:17 maxscale maxscale[18141]: Module 'mariadbmon' loaded from '/usr/lib64/maxscale/libmariadbmon.so'.
7月 06 20:15:17 maxscale maxscale[18141]: Module 'readwritesplit' loaded from '/usr/lib64/maxscale/libreadwritesplit.so'.
7月 06 20:15:17 maxscale maxscale[18141]: Using up to 543.91MiB of memory for query classifier cache
7月 06 20:15:20 maxscale systemd[1]: Started MariaDB MaxScale Database Proxy.

查看端口

?[root@maxscale ~]# ss -antlState ? ? Recv-Q ? ?Send-Q ? ? ? Local Address:Port ? ? ? Peer Address:Port ? Process ? ?LISTEN ? ?0 ? ? ? ? 4096 ? ? ? ? ? ? 127.0.0.1:8989 ? ? ? ? ? ?0.0.0.0:* ? ? ? ? ? ? ? ? LISTEN ? ?0 ? ? ? ? 128 ? ? ? ? ? ? ? ?0.0.0.0:22 ? ? ? ? ? ? ?0.0.0.0:* ? ? ? ? ? ? ? ? LISTEN ? ?0 ? ? ? ? 4096 ? ? ? ? ? ? ? ? ? ? *:3306 ? ? ? ? ? ? ? ? ?*:* ? ? ? ? ? ? ? ? LISTEN ? ?0 ? ? ? ? 128 ? ? ? ? ? ? ? ? ? [::]:22 ? ? ? ? ? ? ? ? [::]:* ? ? ? ? ? ? ? ? [root@maxscale ~]# ss -antlpState ? ? ?Recv-Q ? ? Send-Q ? ? ? ? ?Local Address:Port ? ? ? ? ? Peer Address:Port ? ? Process ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?LISTEN ? ? 0 ? ? ? ? ?4096 ? ? ? ? ? ? ? ?127.0.0.1:8989 ? ? ? ? ? ? ? ?0.0.0.0:* ? ? ? ? users:(("maxscale",pid=15450,fd=19)) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?LISTEN ? ? 0 ? ? ? ? ?128 ? ? ? ? ? ? ? ? ? 0.0.0.0:22 ? ? ? ? ? ? ? ? ?0.0.0.0:* ? ? ? ? users:(("sshd",pid=792,fd=3)) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? LISTEN ? ? 0 ? ? ? ? ?4096 ? ? ? ? ? ? ? ? ? ? ? ?*:3306 ? ? ? ? ? ? ? ? ? ? ?*:* ? ? ? ? users:(("maxscale",pid=15450,fd=27)) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?LISTEN ? ? 0 ? ? ? ? ?128 ? ? ? ? ? ? ? ? ? ?  [::]:22 ? ? ? ? ? ? ? ? ? ? [::]:* ? ? ? ? users:(("sshd",pid=792,fd=4)) ? ? 

查看有哪些服務

?[root@maxscale ~]# maxctrl list services┌────────────────────┬────────────────┬─────────────┬───────────────────┬───────────────────────────┐│ Service ? ? ? ? ? ?│ Router ? ? ? ? │ Connections │ Total Connections │ Targets ? ? ? ? ? ? ? ? ? │├────────────────────┼────────────────┼─────────────┼───────────────────┼───────────────────────────┤│ Read-Write-Service │ readwritesplit │ 0 ? ? ? ? ? │ 0 ? ? ? ? ? ? ? ? │ server1, server2, server3 │└────────────────────┴────────────────┴─────────────┴───────────────────┴───────────────────────────┘

驗證

檢查路由服務狀態

[root@maxscale maxscale]# maxctrl list services
[root@maxscale maxscale]# maxctrl list monitors

?查看后臺服務器有哪些

?[root@maxscale ~]# maxctrl list servers┌─────────┬─────────────────┬──────┬─────────────┬─────────────────┬──────┬───────────────┐│ Server ?│ Address ? ? ? ? │ Port │ Connections │ State ? ? ? ? ? │ GTID │ Monitor ? ? ? │├─────────┼─────────────────┼──────┼─────────────┼─────────────────┼──────┼───────────────┤│ server1 │ 192.168.166.25 │ 3306 │ 0 ? ? ? ? ? │ Master, Running │ ? ? ?│ MySQL-Monitor │├─────────┼─────────────────┼──────┼─────────────┼─────────────────┼──────┼───────────────┤│ server2 │ 192.168.166.27 │ 3306 │ 0 ? ? ? ? ? │ Slave, Running ?│ ? ? ?│ MySQL-Monitor │├─────────┼─────────────────┼──────┼─────────────┼─────────────────┼──────┼───────────────┤│ server3 │ 192.168.166.26 │ 3306 │ 0 ? ? ? ? ? │ Slave, Running ?│ ? ? ?│ MySQL-Monitor │└─────────┴─────────────────┴──────┴─────────────┴─────────────────┴──────┴───────────────┘

實現一主一從

驗證主從同步狀態

從服務器 上檢查復制狀態:

?SHOW SLAVE STATUS\G

關鍵檢查項:

  • Slave_IO_Running: Yes

  • Slave_SQL_Running: Yes

  • Seconds_Behind_Master: 0(表示無延遲)

  • 無錯誤信息(Last_IO_Error/Last_SQL_Error 為空)

1.測試數據同步

(1) 在 主服務器 上操作:
?-- 創建測試數據庫CREATE DATABASE sync_test;USE sync_test;?-- 創建測試表CREATE TABLE test_data (id INT AUTO_INCREMENT PRIMARY KEY,message VARCHAR(50),created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);?-- 插入測試數據INSERT INTO test_data (message) VALUES ('Data from Master');
(2) 在 從服務器 上驗證同步:
?USE sync_test;SELECT * FROM test_data; ?-- 應看到主庫插入的數據

2.測試讀寫分離(通過MaxScale)

假設MaxScale的讀寫分離端口為 4000(需確認實際端口):

?# 通過MaxScale寫入(應路由到主庫)mysql -h <MaxScale_IP> -P 4000 -u user -p -e "INSERT INTO sync_test.test_data (message) VALUES ('Via MaxScale')"?# 通過MaxScale讀取(應路由到從庫)mysql -h <MaxScale_IP> -P 4000 -u user -p -e "SELECT * FROM sync_test.test_data"

預期結果

  • 寫入操作在 主服務器 可見

  • 讀取結果包含所有數據(包括新插入的 Via MaxScale

3.故障切換測試

(1) 模擬主庫故障:
?# 停止主庫MySQL服務(在server1執行)systemctl stop mysql
(2) 檢查MaxScale狀態:
?maxctrl list servers

預期變化

  • server1 狀態變為 Down

  • server2 自動提升為 Master

(3) 驗證新主庫寫入:
?-- 通過MaxScale寫入(應路由到新的主庫server2)INSERT INTO sync_test.test_data (message) VALUES ('New Master Write');
(4) 恢復舊主庫并檢查同步:
?# 重啟server1的MySQLsystemctl start mysql?# 在server1上重新配置為從庫CHANGE MASTER TOMASTER_HOST='192.168.72.129', ?-- 指向新主庫server2MASTER_PORT=3366,MASTER_USER='repl_user',MASTER_PASSWORD='password';START SLAVE;

關鍵命令總結

操作命令
檢查復制狀態SHOW SLAVE STATUS\G
強制切換主庫maxctrl call command mariadbmon failover MySQL-Monitor
查看服務器狀態maxctrl list servers
驗證數據同步主庫寫入 → 從庫查詢

?注意:實際測試前請確認:

  1. MaxScale配置文件中定義的讀寫分離端口([RW Split Router]

  2. 數據庫賬號需有復制權限(主從同步)和遠程訪問權限(MaxScale連接)

測試?

用客戶機連接maxscale

?username:adminpassword:admin

會發現進行讀操作時,是在slave的從數據庫上執行;在進行寫操作時,是在master主數據庫上執行

總結:

MySQL主從復制與讀寫分離的核心價值可歸納為以下三點:

  1. ?性能與擴展性提升?
    • 通過讀寫分離,將讀請求分散到多個從庫,顯著降低主庫壓力,支撐高并發查詢場景(如電商、社交平臺);
    • 橫向擴展從庫數量可應對業務增長,避免單機硬件瓶頸。
  2. ?高可用與數據安全?
    • 主庫故障時,從庫可快速切換為新主庫(Failover),保障服務連續性;
    • 從庫作為實時數據備份,防止主庫數據丟失。
  3. ?架構靈活性與成本優化?
    • 支持異步復制(默認)、半同步復制(平衡安全與延遲)及混合復制模式(MIXED),適應不同業務一致性要求;
    • 通過中間件(如MyCat、MySQL Router)實現透明路由,減少應用層改造成本。

?需規避的風險與優化方向?:

  • ?數據延遲?:異步復制可能因網絡或從庫性能導致同步延遲,可通過半同步復制、并行處理或優化網絡緩解;
  • ?單點故障?:建議采用雙主復制或級聯架構增強容災能力;
  • ?一致性校驗?:定期使用工具(如pt-table-checksum)檢測主從數據差異,避免邏輯沖突。

復制模式對比?

?類型?數據安全性延遲適用場景
異步復制高性能場景(默認)

8

半同步復制交易類業務

5

11

全同步復制強一致性需求

5

????????未來分布式數據庫(如NewSQL)可能逐步替代傳統架構,但現階段MySQL主從復制與讀寫分離仍是平衡性能、成本與穩定性的最優解。?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/87738.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/87738.shtml
英文地址,請注明出處:http://en.pswp.cn/web/87738.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據庫-元數據表

1. 什么是元數據表元數據&#xff1a;數據的數據&#xff0c;用以描述數據的信息也是數據&#xff0c;被稱為元數據2. 獲取元數據的方法MySQL提供了以下三種方法用于獲取數據庫對象的元數據&#xff1a;show語句從INFORMATION_SCHEMA數據庫里查詢相關表&#xff08;information…

【STM32】通用定時器PWM

STM32 通用定時器 PWM 輸出完全解析&#xff08;以 TIM3_CH1 為例&#xff09; PWM 輸出基本原理 PWM&#xff08;Pulse Width Modulation&#xff09;即脈沖寬度調制&#xff0c;是由定時器通過比較 CNT 與 CCR 寄存器實現的。 信號產生原理&#xff1a; ARR 決定周期&#…

python學習打卡:DAY 21 常見的降維算法

知識點回顧&#xff1a; LDA線性判別PCA主成分分析t-sne降維 還有一些其他的降維方式&#xff0c;也就是最重要的詞向量的加工&#xff0c;我們未來再說 浙大疏錦行

基于SpringBoot和Leaflet集成在線天氣服務的區縣當前天氣WebGIS實戰

目錄 前言 一、需求描述 1、功能需求 2、技術實現流程 二、SpringBoot后臺實現 1、控制層實現 2、區縣數據返回 三、WebGIS前端實現 1、區位信息展示 2、天氣信息展示 四、成果展示 1、魔都上海 2、蜀地成都 3、湖南桂東 五、總結 前言 在當今數字化時…

文心開源:文心大模型4.5系列全面開放,AI普惠時代加速到來

一場由4240億參數模型領銜的開源盛宴&#xff0c;正在重塑中國AI生態的底層邏輯 2025年6月30日&#xff0c;百度如約宣布全面開源其旗艦產品——文心大模型4.5系列。一次性開源10款模型&#xff0c;覆蓋從4240億參數的MoE多模態巨無霸到輕巧的0.3B端側模型&#xff0c;并同步開…

【運算放大器專題】基礎篇

1.1 運算放大器是放大了個寂寞嗎&#xff1f;—初識運算放大器 為了解決震蕩問題&#xff0c;人為加了一些補償網絡之后導致的高頻特性差 1.2歐姆定律和獨立源 1正弦2方波3脈沖 電壓源是平行于i軸的橫線 1.3有伴源和運放緩沖器 有伴指的是有電阻&#xff0c;有伴是壞事&#…

英偉達 jetson nano 從NFS啟動,使用英偉達提供的rootfs根文件系統

0、目標 為了方便驅動階段的開發&#xff0c;并且使用英偉達提供的上層應用&#xff0c;這里希望使jetson nano 從NFS啟動&#xff0c;同時使用英偉達提供的rootfs根文件系統。 1、硬件準備 確保jetson nano 板子和開發主機之間使用網線進行連接&#xff08;保持板子和開發主…

廣州華銳互動:以創新科技賦能教育,開啟沉浸式學習?

在教育領域&#xff0c;廣州華銳互動致力于打破傳統教學的局限性&#xff0c;為師生們帶來全新的沉浸式學習體驗。廣州華銳互動通過開發 VR 虛擬教學課件&#xff0c;將抽象的知識轉化為生動、逼真的虛擬場景&#xff0c;讓學生能夠身臨其境地感受知識的魅力 。比如在歷史課上&…

Grok 4 最新技術評測與發布指南

TL;DR&#xff1a;馬斯克跳過Grok 3.5直接發布Grok 4&#xff0c;計劃在7月4日后上線&#xff0c;專注編程模型優化&#xff0c;這次"極限迭代"能否讓馬斯克在AI軍備競賽中翻盤&#xff1f; &#x1f4cb; 文章目錄 &#x1f680; Grok 4發布概況&#x1f3c6; Grok…

為什么音視頻通話需要邊緣加速

? 主要原因 ? 降低傳輸延遲 用戶與邊緣節點之間通常1-2跳即可完成連接&#xff0c;避免跨國、跨運營商長鏈路傳輸 保障音視頻信令、媒體流快速到達&#xff0c;控制端到端延遲 ? 提升弱網環境下的連接穩定性 邊緣節點具備鏈路優化、丟包補償、轉發中繼功能 即使在WiFi切…

小架構step系列05:Springboot三種運行模式

1 概述 前面搭建工程的例子&#xff0c;運行的是一個桌面程序&#xff0c;并不是一個Web程序&#xff0c;在這篇中我們把它改為Web程序&#xff0c;同時從啟動角度看看它們的區別。 2 Web模式 2.1 桌面例子 回顧一下前面的例子&#xff0c;其pom.xml的配置如下&#xff1a;…

LoRaWAN的設備類型有哪幾種?

LoRaWAN&#xff08;Long Range Wide Area Network&#xff09;是一種專為物聯網&#xff08;IoT&#xff09;設備設計的低功耗、長距離通信協議。它根據設備的功能和功耗需求&#xff0c;將設備分為三種類型&#xff1a;Class A、Class B 和 Class C。每種設備類型都有其獨特的…

三維目標檢測|Iou3D 代碼解讀一

本文對OpenPCDet項目中的iou3d模塊中的iou3d_nms_kernel.cu代碼進行解讀&#xff0c;本次解決的函數是box_overlap&#xff0c;它的輸入是兩個包圍盒&#xff0c;輸出是兩個包圍盒在bev下的重疊面積&#xff0c;計算流程是 確定box_a和box_b的四個角落坐標 從包圍盒中提取坐標值…

探索實現C++ STL容器適配器:優先隊列priority_queue

前引&#xff1a; 在算法競賽中&#xff0c;選手們常常能在0.01秒內分出勝負&#xff1b;在實時交易系統中&#xff0c;毫秒級的延遲可能意味著數百萬的盈虧&#xff1b;在高并發服務器中&#xff0c;每秒需要處理數萬條不同優先級的請求——這些系統背后&#xff0c;都隱藏著同…

一、Dify 私有部署、本地安裝教程(LInux-openeuler)

官網&#xff1a;Dify AI Plans and Pricing 1.找到下載的位置。 2.可以切換文檔為中午文檔。 3.本次安裝使用Docker Compose 安裝&#xff0c;可以大致看一下文檔描述的配置信息要求。 4.各個版本信息&#xff0c;本次下載1.5.1版本&#xff0c;你也可以選擇安裝其他版本。 …

GASVM+PSOSVM+CNN+PSOBPNN+BPNN軸承故障診斷

一、各算法基本原理與技術特點 1. GASVM&#xff08;遺傳算法優化支持向量機&#xff09; 原理&#xff1a; 利用遺傳算法&#xff08;GA&#xff09;優化SVM的超參數&#xff08;如懲罰因子 C C C 和核函數參數 g g g&#xff09;。遺傳算法通過模擬自然選擇機制&#xff…

Python實例練習---魔法方法

&#xff08;主頁有對應知識點^V^&#xff09; 【練習要求】 針對知識點Python面向對象的魔法方法安排的本實例。要求實現&#xff1a;用__init__魔法方法定義書的長&#xff0c;寬&#xff0c;高&#xff0c;最后用__str__輸出返回值 【重要步驟提示】 定義class書類 2、使…

【從0-1的CSS】第3篇:盒子模型與彈性布局

文章目錄 盒子模型內容區content內邊距padding邊框border外邊距margin元素的寬度高度box-sizing屬性content-box&#xff1a;設置的width和height就是內容區的width和heightborder-box:設置的width和height是context padding border的width和height 彈性布局Flex容器的屬性fl…

設置LInux環境變量的方法和區別_Ubuntu/Centos

Linux環境變量可以通過export實現&#xff0c;也可以通過修改幾個文件來實現 1 通過文件設置LInux環境變量 首先是設置全局環境變量&#xff0c;對所有用戶都會生效 /etc/profile&#xff1a;該文件為系統的每個用戶設置環境信息&#xff0c;當用戶登錄時&#xff0c;該文件…

python緩存裝飾器實現方案

寫python的時候突然想著能不能用注解于是就寫了個這個 文章目錄 原始版改進點 原始版 import os import pickle import hashlib import inspect import functoolsdef _generate_cache_filename(func, *args, **kwargs):"""生成緩存文件名的內部函數""…