基于centos7.9搭建MariaDB10.5高可用集群

MariaDB-HA

基于centos7.9搭建MariaDB10.5数据库高可用集群,对标mysql5.7

节点 IP
node1 192.168.200.101
node2 192.168.200.102
node3 192.168.200.103

环境初始化

bash 复制代码
#!/bin/bash

# 定义节点信息
NODES=("192.168.200.101 node1" "192.168.200.102 node2" "192.168.200.103 node3")

# 定义当前节点的密码(默认集群统一密码)
HOST_PASS="000000"

# 时间同步的目标节点
TIME_SERVER=node1

# 时间同步的地址段
TIME_SERVER_IP=192.160.200.0/24

# 欢迎界面
cat > /etc/motd <<EOF
 ################################
 #    Welcome  to  mycluster    #
 ################################
EOF

#禁用selinux
sed -i 's/SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config
setenforce 0

#firewalld
systemctl stop firewalld
systemctl disable firewalld  >> /dev/null 2>&1

#关闭IPtables,清空规则
yum install  iptables-services  -y
if [ 0  -ne  $? ]; then
        echo -e "\033[31mThe installation source configuration errors\033[0m"
        exit 1
fi
systemctl restart iptables
iptables -F
iptables -X
iptables -Z
/usr/sbin/iptables-save
systemctl stop iptables
systemctl disable iptables

#禁用NetworkManager
systemctl stop NetworkManager >> /dev/null 2>&1
systemctl disable NetworkManager >> /dev/null 2>&1
yum remove -y NetworkManager firewalld
systemctl restart network

# 优化ssh连接
sed -i -e 's/#UseDNS yes/UseDNS no/g' -e 's/GSSAPIAuthentication yes/GSSAPIAuthentication no/g' /etc/ssh/sshd_config
systemctl reload sshd

# 修改主机名
for node in "${NODES[@]}"; do
  ip=$(echo "$node" | awk '{print $1}')
  hostname=$(echo "$node" | awk '{print $2}')

  # 获取当前节点的主机名和 IP
  current_ip=$(hostname -I | awk '{print $1}')
  current_hostname=$(hostname)

  # 检查当前节点与要修改的节点信息是否匹配
  if [[ "$current_ip" == "$ip" && "$current_hostname" != "$hostname" ]]; then
    echo "Updating hostname to $hostname on $current_ip..."
    hostnamectl set-hostname "$hostname"

    if [ $? -eq 0 ]; then
      echo "Hostname updated successfully."
    else
      echo "Failed to update hostname."
    fi

    break
  fi
done

# 遍历节点信息并添加到 hosts 文件
for node in "${NODES[@]}"; do
  ip=$(echo "$node" | awk '{print $1}')
  hostname=$(echo "$node" | awk '{print $2}')

  # 检查 hosts 文件中是否已存在相应的解析
  if grep -q "$ip $hostname" /etc/hosts; then
    echo "Host entry for $hostname already exists in /etc/hosts."
  else
    # 添加节点的解析条目到 hosts 文件
    sudo sh -c "echo '$ip $hostname' >> /etc/hosts"
    echo "Added host entry for $hostname in /etc/hosts."
  fi
done

if [[ ! -s ~/.ssh/id_rsa.pub ]]; then
    ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q -b 2048
fi

# 检查并安装 expect 工具
if ! which expect &> /dev/null; then
    echo "expect 工具未安装,正在安装 expect..."
    sudo yum install -y expect
fi

# 遍历所有节点
for node in "${NODES[@]}"; do
    ip=$(echo "$node" | awk '{print $1}')
    hostname=$(echo "$node" | awk '{print $2}')

    expect -c "
        set timeout -1
        spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $hostname
        expect {
            \"*password:*\" { send -- \"$HOST_PASS\r\"; exp_continue }
            \"*(yes/no)*\" { send -- \"yes\r\"; exp_continue }
            eof { exit 1 }
        }
    "
done

# 时间同步
if [[ $name == $TIME_SERVER ]]; then
    # 配置当前节点为时间同步源
    sed -i '3,6s/^/#/g' /etc/chrony.conf
    sed -i "7s/^/server $TIME_SERVER iburst/g" /etc/chrony.conf
    echo "allow $TIME_SERVER_IP" >> /etc/chrony.conf
    echo "local stratum 10" >> /etc/chrony.conf
else
    # 配置当前节点同步到目标节点
    sed -i '3,6s/^/#/g' /etc/chrony.conf
    sed -i "7s/^/server $TIME_SERVER iburst/g" /etc/chrony.conf
fi

# 重启并启用 chrony 服务
systemctl restart chronyd
systemctl enable chronyd

echo "###############################################################"
echo "#################      集群初始化成功     #####################"
echo "###############################################################"

安装MariaDB

官网

三台节点操作

bash 复制代码
tar -xf mariadb-10.5.26-rhel-7-x86_64-rpms.tar -C /opt/

配置centos7.9仓库

sql 复制代码
mount /dev/sr0 /mnt/
sql 复制代码
mv /etc/yum.repos.d/* /media/
bash 复制代码
cat >> /etc/yum.repos.d/local.repo << EOF
[centos]
name=centos
baseurl=file:///mnt
gpgcheck=0
enabled=1
[DB]
name=DB
baseurl=file:///opt/mariadb-10.5.26-rhel-7-x86_64-rpms
gpgcheck=0
enabled=1
EOF

清理旧依赖

bash 复制代码
rpm  -qa  |  grep  mariadb
rpm  -e  --nodeps  mariadb-libs-5.5.68-1.el7.x86_64

安装数据库

bash 复制代码
yum install -y MariaDB-server MariaDB

启动数据库

bash 复制代码
systemctl enable --now mariadb

默认没有密码,手动设置

bash 复制代码
mysqladmin -uroot password root

配置集群

Galera Cluster 是 Galera 技术的一种应用实现,专为高可用性和数据一致性设计,通常用于支持 Percona XtraDB Cluster 和 MariaDB Cluster。它的核心特性包括多主复制、同步复制以及自动成员管理等,下面是对其主要特性的介绍。

  • Galera 的核心功能

    多主复制(Multi-Master Replication)

  • 集群中的每个节点都是一个主节点,应用可以对任意节点进行读写操作。

    多主复制提供了数据写入的灵活性和更高的可用性,当一个节点发生故障时,其他节点可以继续处理读写请求。

    同步复制(Synchronous Replication)

  • 数据在多个节点间同步写入,确保数据的一致性。

    使用 "并发控制"(Certification-based Replication),在事务提交时进行认证,以确保数据的同步和一致。

    自动故障转移与恢复(Automatic Failover and Recovery)

  • 节点发生故障时,集群会自动重新分配工作负载到其他节点。

    故障节点修复并重新加入后会自动同步数据,保持数据一致性。

    并行复制(Parallel Replication)

  • 支持多线程并行复制,优化数据同步效率,提高复制性能。

    一致性检查(Consistency Guarantees)

  • Galera 支持强一致性,即在所有节点中保证相同的数据副本,这对金融等高数据一致性要求的业务尤为重要。

    网络分区处理(Split-Brain Handling)

  • Galera 使用 Quorum 算法来管理节点的状态,避免在网络分区时产生脑裂。

    网络分区中,Galera 允许大多数节点继续工作,而隔离掉少数节点,确保集群的一致性。

    Galera 的工作机制

  • 认证(Certification):当一个事务在一个节点提交时,Galera 会在其他节点上进行一致性检查,确保不冲突后再提交到每个节点上。

  • 全同步(Whole-Sync):Galera 采用全同步方式将数据块复制到各节点,保证每个节点的数据库副本完全一致。

    WSREP API:Galera 使用的 Write Set Replication(WSREP)API 提供了与数据库服务器的接口,实现集群之间的数据写入集成。

三台节点关闭数据库

bash 复制代码
systemctl stop mariadb

三节点修改配置文件

bash 复制代码
cat > /etc/my.cnf.d/server.cnf << eof
[server]
# 服务器通用设置
[mysqld]
# MySQL守护进程的专用设置

[galera]
# Galera 相关配置,用于高可用集群配置
wsrep_on=ON                          # 启用 Galera 复制
wsrep_provider=/usr/lib64/galera-4/libgalera_smm.so  # Galera 提供程序的库路径
wsrep_cluster_address="gcomm://192.168.200.101,192.168.200.102,192.168.200.103"  # 集群中各节点的IP地址列表
binlog_format=row                    # 使用行级二进制日志格式(Galera 必须)
default_storage_engine=InnoDB        # 设置默认存储引擎为 InnoDB
innodb_autoinc_lock_mode=2           # 配置自增锁模式,确保Galera兼容性

# 网络绑定
bind-address=0.0.0.0                 # 允许所有网络接口连接到数据库服务
# 可选设置(根据需求调整)
wsrep_slave_threads=1                # 设置并行复制线程数
innodb_flush_log_at_trx_commit=0     # 提高写性能,适合非关键数据场景

[embedded]
# 内嵌服务器的设置(一般不需改动)
[mariadb]
# MariaDB 专用设置
[mariadb-10.5]
# 仅适用于 MariaDB 10.5 版本及以上的设置
eof

node1节点启动集群

bash 复制代码
galera_new_cluster

其他节点重启数据库

bash 复制代码
systemctl restart mariadb

验证

bash 复制代码
[root@node1 ~]# mysql -uroot -proot
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 7
Server version: 10.5.26-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)]> show status like "wsrep_ready";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wsrep_ready   | ON    |
+---------------+-------+
1 row in set (0.001 sec)

MariaDB [(none)]> show status like "wsrep_cluster_size";
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 3     |
+--------------------+-------+
1 row in set (0.001 sec)

MariaDB [(none)]>

关闭集群,配置参数,三台节点逐个停止,从3到1

编辑配置文件

bash 复制代码
cat >> /etc/my.cnf <<eof

[mysqld]
# 大小写不敏感设置
lower_case_table_names=1  # 设置为 1 使数据库表名不区分大小写

# 性能优化设置
max_connections=1000  # 最大连接数
innodb_flush_log_at_trx_commit=2  # 提高写入性能
innodb_buffer_pool_size=3G  # 根据系统内存调整
thread_cache_size=100  # 线程缓存
table_open_cache=4096  # 表缓存
wsrep_slave_threads=4  # 根据 CPU 核数增加并行线程
innodb_locks_unsafe_for_binlog=1  # 提升并行性能

# 其他可选设置
innodb_log_file_size=256M  # 日志文件大小
innodb_flush_method=O_DIRECT  # 刷新方法
innodb_read_io_threads=4  # 读取 I/O 线程数
innodb_write_io_threads=4  # 写入 I/O 线程数
eof

重新启动

bash 复制代码
galera_new_cluster

启动节点启动

bash 复制代码
systemctl restart mariadb

查看

bash 复制代码
[root@node1 ~]# mysql -uroot -proot -e'show status like "wsrep_cluster_size";'
+--------------------+-------+
| Variable_name      | Value |
+--------------------+-------+
| wsrep_cluster_size | 3     |
+--------------------+-------+
[root@node1 ~]#
相关推荐
A小辣椒15 小时前
TShark:Wireshark CLI 功能
linux
A小辣椒19 小时前
TShark:基础知识
linux
AlfredZhao21 小时前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao1 天前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
用户9718356334662 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪2 天前
linux 拷贝文件或目录到指定的位置
linux
摇滚侠2 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
bush42 天前
嵌入式linux学习记录十四、术语
linux·嵌入式
载数而行5202 天前
Linux 11 动态监控指令top
linux
不会C语言的男孩3 天前
Linux 系统编程 · 第 8 章:进程基础
linux·c语言