Linux运维开发

MySQL主从复制(一主一从)

2018-07-19  本文已影响20人  InnocenceYWQ

一. 为什么要使用MySQL主从复制



二. 安装MySQL服务器

CentOS 7.0中,已经使用MariaDB替代了MySQL数据库,功能和MySQL差不多,这里我们使用MariaDB服务器进行MySQL主从复制。

安装所需软件包:
[root@centos7 ~]#yum -y install httpd mariadb-server mariadb php php-mysql

启动相关服务:
[root@centos7 ~]# systemctl start  httpd
[root@centos7 ~]# systemctl start  mariadb 

测试数据库连接: 
[root@centos7 ~]# mysql -u root –p123456 –h 10.10.10.68

为root用户设置密码
[root@centos7 ~]# mysqladmin -u root password "123456"

启动服务后查看默认的数据库:

[root@xuegod64 ~]# systemctl start  mariadb 
[root@xuegod64 ~]# mysql -u root 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.56-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.01 sec)


通过密码登录:

[root@xuegod64 ~]# mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 11
Server version: 5.5.56-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

三.主从复制

环境准备.png
[root@xuegod64 html]# mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 12
Server version: 5.5.56-MariaDB MariaDB Server

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

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

MariaDB [(none)]> create database HA;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> use HA;
Database changed
MariaDB [HA]> create table T1(
    -> id int ,
    -> name varchar(20));
Query OK, 0 rows affected (0.03 sec)

MariaDB [HA]> show tables;
+--------------+
| Tables_in_HA |
+--------------+
| T1           |
+--------------+
1 row in set (0.00 sec)

配置my.cnf:

log-bin=mysql-bin-master  #启用二进制日志  
server-id=1   
binlog-do-db=HA #可以被从服务器复制的库, 二进制需要同步的数据库名
binlog-ignore-db=mysql  

重启服务
查看二进制日志:

ls /usr/local/mysql/data/

保持同步

复制前要保证同步的数据库一致
mysqldump  -uroot -p123456 HA >HA.sql  #可以导出数据库

导出数据

将导出的数据库传给从服务器
方法:scp HA.sql  10.10.10.64:/root

登录slave服务器,执行以下命令:

mysql>stop slave;    #停止slave
mysql> change master to master_host='10.10.10.63',master_user='slave',master_password='123456';
mysql> start slave;    #启动slave

查看Slave_IO_Running ,Slave_SQL_Running为yes即可。

上一篇 下一篇

猜你喜欢

热点阅读