我是一只小白兔~
分类: Mysql/postgreSQL
2016-04-14 15:12:34
1、 在两台机子上装好mysql,ip分别为192.168.205.237(primary)、192.168.205.241(slave)
2、 在主库上创建复制用户,并授予replication slave权限,可以备库进行连接
mysql> grant replication slave on *.* to identified by ‘luoxuan’;
Query OK, 0 rows affected (0.01 sec)
3、 修改my.cnf配置文件,开启binlog,设置server-id,重启mysql服务
增加如下内容:
log-bin = /opt/mysql/mysql/log
server-id = 1# /etc/init.d/mysql stop
Shutting down MySQL
.. SUCCESS!
# mysqld_safe –defaults-file=/etc/my.cnf –user=mysql &
25699
# Starting mysqld daemon with databases from /opt/mysql/mysql/data
4、 在主服务器上,设置读锁有效,确保没有数据库操作,以便获得一致性快照
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)
5、 显示主库的二进制名及偏移值,为了从库启动后,从这个点开始进行数据恢复
mysql> show master status;
+——————+———-+————–+——————+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+——————+———-+————–+——————+
| mysql-bin.000001 | 98 | | |
+——————+———-+————–+——————+
1 row in set (0.05 sec)
6、 可以用多种方法来生成主库的备份,恢复到从库去。这里用cp数据文件(mysql服务停止)
tar -cvf data.tar data
7、 主库备份完毕后,可以恢复写操作,接下来只要操作从库就可以了
mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)
8、 将备份文件传到从库的相应目录
9、 修改从库的server-id为2,如果要复制到多个从库,那么server-id都应该不同
# vi /etc/my.cnf
“/etc/my.cnf” 4 lines, 90 characters
[mysqld]
basedir=/opt/mysql/mysql
datadir=/opt/mysql/mysql/data
default-character-set=gbk
server-id=2
10、在从库,使用—skip-slave-start选项启动从库,这样就不会启动从库的复制进程,以便进一步配置从库。
# mysqld_safe –defaults-file=/etc/my.cnf –user=mysql –skip-slave-start &
4911
# Starting mysqld daemon with databases from /opt/mysql/mysql/data
11、对从库进行设置,指定复制用户及主库IP、port及复制日志文件、位置。
mysql> change master to
-> master_host =’192.168.205.237′,
-> master_port = 3306,
-> master_user = ‘luoxuan’,
-> master_password = ‘luoxuan’,
-> master_log_file= ‘mysql-bin.000001′,
-> master_log_pos=98;
Query OK, 0 rows affected (0.01 sec)
12、启动slave进程
mysql> start slave;
Query OK, 0 rows affected (0.00 sec)
13、在从库上执行
mysql> show processlist \G;
*************************** 1. row ***************************
Id: 2
User: root
Host: localhost
db: NULL
Command: Query
Time: 0
State: NULL
Info: show processlist
*************************** 2. row ***************************
Id: 3
User: system user
Host:
db: NULL
Command: Connect
Time: 29
State: Waiting for master to send event
Info: NULL
*************************** 3. row ***************************
Id: 4
User: system user
Host:
db: NULL
Command: Connect
Time: 29
State: Has read all relay log; waiting for the slave I/O thread to update it
Info: NULL
3 rows in set (0.00 sec)
这说明从库连上主库,并开始接受日志。
我们来验证一下:
主:
mysql> create table xiyan(a int) engine = innodb;
Query OK, 0 rows affected (0.02 sec)mysql> insert into xiyan values(1);
Query OK, 1 row affected (0.00 sec)mysql> insert into xiyan values(2);
Query OK, 1 row affected (0.00 sec)
从:
mysql> show tables like ‘xiyan%’;
+—————————-+
| Tables_in_luoxuan (xiyan%) |
+—————————-+
| xiyan |
+—————————-+
1 row in set (0.00 sec)
mysql> select * from xiyan;
+——+
| a |
+——+
| 1 |
| 2 |
+——+
2 rows in set (0.00 sec)