如何在Linux上配置高可用的資料庫主從複製監控
引言:
在現代的技術環境中,資料庫是一個關鍵元件,許多應用程式都依賴它們。出於可用性和資料保護的考慮,資料庫的高可用性和主從複製都是非常重要的功能。本文將介紹如何在Linux上配置高可用的資料庫主從複製監控,透過範例程式碼來示範操作步驟。
主從複製的工作原理:
主從複製是一種常見的資料庫複製方法,其中一個資料庫伺服器作為主伺服器(Master),而其他伺服器則作為從伺服器(Slave)。主伺服器接收的寫入操作將複製到從伺服器。這種架構提供了資料冗餘、讀寫分離和故障復原的好處。
配置主伺服器:
首先,我們需要安裝資料庫伺服器。本文以MySQL為例。
安裝MySQL伺服器:
sudo apt update sudo apt install mysql-server
#設定主伺服器:
編輯MySQL設定檔:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
在文件中找到以下行,並進行修改:
bind-address = 0.0.0.0 server-id = 1 log_bin = /var/log/mysql/mysql-bin.log
#重啟MySQL服務:
sudo systemctl restart mysql
設定從伺服器:
sudo apt update sudo apt install mysql-server
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = 0.0.0.0 server-id = 2 log_bin = /var/log/mysql/mysql-bin.log relay_log = /var/log/mysql/mysql-relay-bin.log
sudo systemctl restart mysql
##設定主從關係:
在主伺服器上建立一個用於複製的使用者:
mysql -u root -p GRANT REPLICATION SLAVE ON *.* TO 'replication_user'@'%' IDENTIFIED BY 'password'; FLUSH PRIVILEGES; EXIT;
mysql -u root -p CHANGE MASTER TO MASTER_HOST='主服务器的IP地址', MASTER_USER='replication_user', MASTER_PASSWORD='password'; START SLAVE; EXIT;
在主伺服器上建立一個資料庫和表,並插入一些資料。然後,在從伺服器上驗證是否能夠看到相應的資料。
sudo apt update sudo apt install python3-pip pip3 install mysql-connector-python pip3 install smtplib
import smtplib import mysql.connector from email.mime.text import MIMEText def send_email(message): sender = "your_email@gmail.com" receiver = "recipient_email@gmail.com" subject = "Database Replication Alert" msg = MIMEText(message) msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver try: with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(sender, "your_password") smtp.sendmail(sender, receiver, msg.as_string()) print("Email sent successfully!") except Exception as e: print("Email failed to send: " + str(e)) def monitor_replication(): try: connection = mysql.connector.connect(host="localhost", user="replication_user", password="password", database="test") cursor = connection.cursor() cursor.execute("SELECT COUNT(*) FROM my_table") result = cursor.fetchone() cursor.close() connection.close() print("Replication is working fine, number of records: " + str(result[0])) except mysql.connector.Error as error: message = "Replication failed: " + str(error) print(message) send_email(message) if __name__ == "__main__": monitor_replication()
以上是如何在Linux上配置高可用的資料庫主從複製監控的詳細內容。更多資訊請關注PHP中文網其他相關文章!