MariaDB主从复制和读写分离

时间:2022-02-20 14:52:16

一、基础环境

MariaDB主从复制和读写分离

MariaDB主从复制和读写分离

二、配置MariaDB服务

1.安装MariaDB

# yum install -y mariadb mariadb-server

# systemctl start mariadb

# systemctl enable mariadb

2.安全配置

# mysql_secure_installation

3.调优

# vi /etc/my.cnf.d/server.cnf

在[mysqld]插入以下项

[mysqld]
skip_name_resolve=ON
innodb_file_per_table=ON

4.授权访问

MariaDB [(none)]> use mysql;

MariaDB [mysql]> grant all privileges on *.* to 'root'@'ip' identified by 'your passwd';      //授权制定ip访问

MariaDB [mysql]> grant all privileges on *.* to 'root'@'%' identified by 'your passwd';       //授权所有ip访问

MariaDB [mysql]> flush privileges;

MariaDB [mysql]> \q

三、配置主从同步

1.配置node01主节点

# vim /etc/my.cnf.d/server.cnf

在 [mysqld] 追加以下项

MariaDB主从复制和读写分离

[mysqld]
skip_name_resolve=ON
innodb_file_per_table=ON server_id=1
log_bin=master-bin

更改配置后重启mariadb服务

# systemctl restart mariadb

创建用户tichy,slave节点通过用户tichy复制数据

MariaDB [mysql]> grant replication slave,replication client on *.* to 'tichy'@'10.100.1.%' identified by 'tichy';

MariaDB [mysql]> flush privileges;

查看主节点状态

MariaDB [(none)]> show master status;

MariaDB主从复制和读写分离

2.配置node02和node03从节点

# vim /etc/my.cnf.d/server.cnf

MariaDB主从复制和读写分离

[mysqld]
skip_name_resolve=ON
innodb_file_per_table=ON server_id=2
relay_log=relay-log
read_only=ON

指向主库

MariaDB [(none)]> change master to master_host='10.100.1.121',master_user='tichy',master_password='tichy',master_log_file='master-bin.000001',master_log_pos=245;

MariaDB主从复制和读写分离

node03和node02配置方法一样,但server_id一定要区分开

MariaDB主从复制和读写分离

3.主从测试

在node01主节点上创建数据库、创建表、插入数据

创建库

MariaDB [(none)]> create database tichy;

创建表

MariaDB [(none)]> use tichy;
Database changed
MariaDB [tichy]> create table person(id int, name varchar(20), age int);
Query OK, 0 rows affected (0.01 sec)

插入数据

MariaDB [tichy]> insert into person values('1','tom','28'),('2','jerry','27');

查看库表

MariaDB [tichy]> select * from person;
+------+-------+------+
| id | name | age |
+------+-------+------+
| 1 | tom | 28 |
| 2 | jerry | 27 |
+------+-------+------+
2 rows in set (0.00 sec)

在node02和node03从节点上查询

MariaDB [(none)]> select * from tichy.person;
+------+-------+------+
| id | name | age |
+------+-------+------+
| 1 | tom | 28 |
| 2 | jerry | 27 |
+------+-------+------+
2 rows in set (0.00 sec)

可以看到库表数据,主从复制配置成功。

四、主从读写分离

1.配置mysql-proxy

# wget https://cdn.mysql.com/archives/mysql-proxy/mysql-proxy-0.8.5-linux-glibc2.3-x86-64bit.tar.gz

MariaDB主从复制和读写分离