[數據庫] MariaDB安裝及使用


一、安裝MariaDB

1.使用官方源安裝marisdb

如果使用阿里雲的源,目前的版本號為5.5.64。如果想安裝最新的10.x版本,則需要使用MariaDB的官方源。

1)配置官方源:

在/etc/yum.repos.d/下創建MariaDB.repo:

[root@centos-db ~]# cd /etc/yum.repos.d/
[root@centos-db yum.repos.d]# touch MariaDB.repo
[root@centos-db yum.repos.d]# vi MariaDB.repo

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/PRM-GPG-KEY-MariaDB
gpgcheck=1

執行命令:

[root@centos-db yum.repos.d]# yum clean all
[root@centos-db yum.repos.d]# yum makecache

2)安裝MariaDB-server和MariaDB-client

配置好MariaDB官方源以后,使用以下命令安裝:

[root@centos-db yum.repos.d]# yum install MariaDB-server MariaDB-client

可以看到具體的版本號:

============================================================================================================================================================================================================================================
 Package                                                         Arch                                           Version                                                               Repository                                       Size
============================================================================================================================================================================================================================================
Installing:
 MariaDB-client                                                  x86_64                                         10.1.44-1.el7.centos                                                  mariadb                                          10 M
 MariaDB-server                                                  x86_64                                         10.1.44-1.el7.centos                                                  mariadb                                          24 M

2.使用阿里源安裝mariadb

如果官方源速度慢,並且我們對新版本沒有特別要求,則可以使用阿里源進行安裝。

1)刪除官方源的repo文件

[root@centos-db yum.repos.d]# cd /etc/yum.repos.d/
[root@centos-db yum.repos.d]# mv MariaDB.repo MariaDB.repo.bk

2)清理緩存

[root@centos-db yum.repos.d]# yum clean all

3)安裝mariadb

[root@centos-db yum.repos.d]# yum install mariadb-server mariadb

注意,使用阿里源安裝時,名字和官方的不一樣,官方的名字是MariaDB-server、MariaDB-client。而阿里源為mariadb-server、mariadb。注意區分大小寫和名稱。

3.啟動MariaDB

使用官方源或阿里源安裝好mariadb后,使用以下命令來管理MariaDB服務:

systemctl status mariadb  # 查看狀態
systemctl start mariadb  # 啟動
systemctl stop mariadb  # 停止
systemctl restart mariadb  # 重啟
systemctl enable mariadb  # 設置開機啟動
systemctl disable mariadb  # 取消開機啟動

啟動mariadb:

[root@centos-db yum.repos.d]# systemctl status mariadb
鈼[0m mariadb.service - MariaDB database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
   Active: active (running) since Wed 2020-01-29 13:40:59 CST; 2s ago
  Process: 1703 ExecStartPost=/usr/libexec/mariadb-wait-ready $MAINPID (code=exited, status=0/SUCCESS)
  Process: 1615 ExecStartPre=/usr/libexec/mariadb-prepare-db-dir %n (code=exited, status=0/SUCCESS)
 Main PID: 1702 (mysqld_safe)
   CGroup: /system.slice/mariadb.service
           鈹溾攢1702 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
           鈹斺攢1864 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket=/var/lib/mysql/mysql.sock

Jan 29 13:40:57 centos-db mariadb-prepare-db-dir[1615]: MySQL manual for more instructions.
Jan 29 13:40:57 centos-db mariadb-prepare-db-dir[1615]: Please report any problems at http://mariadb.org/jira
Jan 29 13:40:57 centos-db mariadb-prepare-db-dir[1615]: The latest information about MariaDB is available at http://mariadb.org/.
Jan 29 13:40:57 centos-db mariadb-prepare-db-dir[1615]: You can find additional information about the MySQL part at:
Jan 29 13:40:57 centos-db mariadb-prepare-db-dir[1615]: http://dev.mysql.com
Jan 29 13:40:57 centos-db mariadb-prepare-db-dir[1615]: Consider joining MariaDB's strong and vibrant community:
Jan 29 13:40:57 centos-db mariadb-prepare-db-dir[1615]: https://mariadb.org/get-involved/
Jan 29 13:40:57 centos-db mysqld_safe[1702]: 200129 13:40:57 mysqld_safe Logging to '/var/log/mariadb/mariadb.log'.
Jan 29 13:40:57 centos-db mysqld_safe[1702]: 200129 13:40:57 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
Jan 29 13:40:59 centos-db systemd[1]: Started MariaDB database server.

二、初始化

使用命令:

mysql_secure_installation
[root@centos-db yum.repos.d]# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):   # 這里直接enter就可以了
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] y   # 1.是否設置root密碼,選擇Y
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y  # 2.是否刪除匿名賬戶,因為不安全,選擇Y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y  # 3.是否允許root用戶遠程登錄,因為要在windows機器上去開發,所以選擇Y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y  # 4.刪除測試數據庫,選擇Y - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y  # 5.是否立即刷新權限表,選擇Y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

三、使用mysql

1.登錄mysql

[root@centos-db yum.repos.d]# mysql -uroot -p
Enter password:   # 輸入root密碼
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 11
Server version: 5.5.64-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)]> 

2.修改服務器字符編碼

1)查看服務器字符編碼

MariaDB [(none)]> \s
--------------
mysql  Ver 15.1 Distrib 5.5.64-MariaDB, for Linux (x86_64) using readline 5.1

Connection id:          11
Current database:
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server:                 MariaDB
Server version:         5.5.64-MariaDB MariaDB Server
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset: latin1 Db characterset: latin1
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /var/lib/mysql/mysql.sock
Uptime:                 10 min 24 sec

Threads: 1  Questions: 30  Slow queries: 0  Opens: 1  Flush tables: 2  Open tables: 27  Queries per second avg: 0.048
--------------

可以看到,mysql服務器字符編碼為latin1,無法顯示中文。並且在這種字符編碼下,創建的數據庫和表都不能插入和顯示中文。

2)修改配置文件

[root@centos-db etc]# vi my.cnf  # 修改/etc/my.cnf配置文件

[mysqld]
character-set-server=utf8

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

添加character-set-server=utf8配置。

3)重啟mariadb服務

systemctl restart mariadb

4)再次查看字符編碼

MariaDB [(none)]> \s
--------------
mysql  Ver 15.1 Distrib 5.5.64-MariaDB, for Linux (x86_64) using readline 5.1

Connection id:          2
Current database:
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server:                 MariaDB
Server version:         5.5.64-MariaDB MariaDB Server
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset: utf8 Db characterset: utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /var/lib/mysql/mysql.sock
Uptime:                 14 sec

Threads: 1  Questions: 4  Slow queries: 0  Opens: 0  Flush tables: 2  Open tables: 26  Queries per second avg: 0.285
--------------

3.創建數據庫和表

1)查看所有數據庫

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

2)創建數據庫

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

查看數據庫創建過程:

MariaDB [mydb]> show create database mydb;
+----------+---------------------------------------------------------------+
| Database | Create Database                                               |
+----------+---------------------------------------------------------------+
| mydb     | CREATE DATABASE `mydb` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+---------------------------------------------------------------+
1 row in set (0.00 sec)

3)使用某個數據庫

MariaDB [(none)]> use mydb;
Database changed
MariaDB [mydb]> 

4)查看所有表

MariaDB [mydb]> show tables;
Empty set (0.00 sec)  # 目前沒有任何表

5)創建一張表

MariaDB [mydb]> create table user_info (id int,name char(50),age int);
Query OK, 0 rows affected (0.00 sec)
MariaDB [mydb]> show tables;
+----------------+
| Tables_in_mydb |
+----------------+
| user_info      |
+----------------+
1 row in set (0.00 sec)

查看表的創建過程:

MariaDB [mydb]> show create table user_info;
+-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table     | Create Table                                                                                                                                              |
+-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
| user_info | CREATE TABLE `user_info` (
  `id` int(11) DEFAULT NULL,
  `name` char(50) DEFAULT NULL,
  `age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

4.表操作

1)插入一條數據

MariaDB [mydb]> insert into user_info (id,name,age) values (1,"張三",32);
MariaDB [mydb]> select * from user_info; +------+--------+------+
| id   | name   | age  |
+------+--------+------+
|    1 | 張三   |   32 |
+------+--------+------+
1 row in set (0.00 sec)

2)查詢數據

MariaDB [mydb]> select * from user_info; +------+--------+------+
| id   | name   | age  |
+------+--------+------+
|    1 | 張三   |   32 |
|    2 | 李四   |   22 |
+------+--------+------+
2 rows in set (0.00 sec)
MariaDB [mydb]> select name,age from user_info where id=1; 
+--------+------+
| name   | age  |
+--------+------+
| 張三   |   32 |
+--------+------+
1 row in set (0.00 sec)

3)刪除一條數據

MariaDB [mydb]> delete from user_info where id=1;
Query OK, 1 row affected (0.00 sec)
MariaDB [mydb]> select * from user_info;
+------+--------+------+
| id   | name   | age  |
+------+--------+------+
|    2 | 李四   |   22 |
+------+--------+------+

4)查看表結構

MariaDB [mydb]> desc user_info;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  |     | NULL    |       |
| name  | char(50) | YES  |     | NULL    |       |
| age   | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

5.管理操作

1)創建用戶

MariaDB [(none)]> create user leokale@'%' identified by '11111111';  # '%'表示用戶'leokale'在所有的主機地址都可以登錄,使用密碼是'11111111'
Query OK, 0 rows affected (0.00 sec)

剛創建好的用戶權限很低,無法創建數據庫。

2)修改用戶密碼

自己修改自己密碼:

MariaDB [mydb]> set password = PASSWORD('123456');
Query OK, 0 rows affected (0.00 sec)

root修改其他用戶密碼:

MariaDB [(none)]> set password for leokale@'%' = PASSWORD("88888888");
Query OK, 0 rows affected (0.00 sec)

3)查看用戶表

[root@centos-db etc]# mysql -uroot -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 5.5.64-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 databases; +--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)

MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> show tables; +---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| host                      |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| proxies_priv              |
| servers                   |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
24 rows in set (0.00 sec)

查看用戶表中的信息:

MariaDB [mysql]> select host,user,password from user; +-----------+---------+-------------------------------------------+
| host      | user    | password                                  |
+-----------+---------+-------------------------------------------+
| localhost | root    | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
| 127.0.0.1 | root    | *4D77515AB2D393245315E18C62709EC959669A89 |
| ::1       | root    | *4D77515AB2D393245315E18C62709EC959669A89 |
| %         | leokale | *E9D057131C22A0D76B4AAD2C61655BDFA706E637 |
+-----------+---------+-------------------------------------------+
4 rows in set (0.00 sec)

可以看到我們創建的leokale用戶。

4)給用戶添加權限

使用grant命令:(grant是授予的意思)

MariaDB [mysql]> grant all privileges on *.* to leokale@'%';
MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

這個命令的意思是,授予所有的權限(all privileges),所有的數據庫和表(*.*),給用戶"leokale"在所有主機登錄時。

使用"leokale"登錄mysql:

[root@centos-db etc]# mysql -uleokale -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 5.5.64-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 databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mysql              |
| performance_schema |
+--------------------+
4 rows in set (0.00 sec)

可以看到,leokale用戶在賦予權限后,可以查詢到所有的數據庫。並且可以進行所有操作。

6.遠程登錄

1)在遠程計算機上安裝mariadb-client,然后使用"leokale"用戶進行遠程登錄:

[root@centos-dbclient ~]# mysql -uleokale -p -h 192.168.1.189
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4
Server version: 5.5.64-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)]> 

可以看到"leokale"用戶可以正常登錄。

2)root用戶遠程登錄

[root@centos-dbclient ~]# mysql -uroot -p -h 192.168.1.189
Enter password: 
ERROR 1045 (28000): Access denied for user 'root'@'192.168.1.190' (using password: YES)

我們發現,root用戶無法遠程登錄;

這是因為root用戶默認不支持所有主機登錄,可以從mysql.user表中看到:

MariaDB [mysql]> select user,host from user;
+---------+-----------+
| user    | host      |
+---------+-----------+
| leokale | %         |
| root    | 127.0.0.1 |
| root    | ::1       |
| root    | localhost |
+---------+-----------+
4 rows in set (0.00 sec)

所以,我們需要給root用戶賦一個可以在任何主機遠程登錄的權限:

MariaDB [mysql]> grant all privileges on *.* to root@'%' identified by '1234567';
Query OK, 0 rows affected (0.00 sec)
MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

注意,這里一定要重新指定一個密碼(遠程登錄密碼和本地密碼不一樣),也就是identified by "密碼"。這里的密碼和在localhost上使用root登錄的密碼不一樣。否則無法遠程登錄。

四、備份和恢復

1.備份數據庫

首先觀察我們自己創建的數據庫有哪些:

MariaDB [(none)]> show databases;       
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mydb2              |
| mydb3              |
| mysql              |
| performance_schema |
+--------------------+
6 rows in set (0.00 sec)

mydb、mydb1、mydb2都是我們自己創建的數據庫;

使用linux命令來備份數據庫:

[root@centos-db ~]# mysqldump -u root -p --all-databases > ~/AllMysql.dump
Enter password: 
[root@centos-db ~]# 

可以看到在/root目錄下生成了一個AllMysql.dump的文件:

[root@centos-db ~]# ll
total 508
-rw-r--r--. 1 root root 515649 Jan 29 17:57 AllMysql.dump
-rw-------. 1 root root   1309 Dec 11 20:27 anaconda-ks.cfg

2.刪除數據庫

MariaDB [(none)]> drop database mydb;  # 刪除mydb
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> drop database mydb2;  # 刪除mydb2
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> drop database mydb3;  # 刪除mydb3
Query OK, 0 rows affected (0.00 sec)

3.恢復數據庫

使用source命令,恢復:

MariaDB [(none)]> source ~/AllMysql.dump

也可以在linux命令行中恢復:

[root@centos-db ~]# mysql -uroot -p < ~/AllMysql.dump 
Enter password: 
[root@centos-db ~]# 

查看是否恢復:

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mydb2              |
| mydb3              |
| mysql              |
| performance_schema |
+--------------------+
6 rows in set (0.00 sec)

可以看到,被我們刪除的數據庫已經恢復。

五、主從復制

1.基本原理

主從的數據同步如下圖所示:

 

當主庫有數據更新時,會將操作寫入到Binary log中,然后從庫會從Binary log中讀取操作命令,並且寫到自己的log中,然后執行命令,向自己的庫中插入數據。這就保證從庫的數據和主庫同步。

2.主庫配置

1)主庫配置文件

[mysqld]
# mysql服務器id
server-id=1 # 指定Binary log文件名
log-bin=mysql-bin

character-set-server=utf8
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

2)登錄數據庫,查看主從狀態

MariaDB [(none)]> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      245 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

可以看到,我們的Binary log文件名, 以及Position(記錄位置)。

3)主庫創建負責同步的用戶

MariaDB [(none)]> create user 'copyer'@'%' identified by '00000000';
Query OK, 0 rows affected (0.00 sec)

4)賦予拷貝權限:

MariaDB [(none)]> grant replication slave on *.* to 'copyer'@'%';  # 授予其slave身份
Query OK, 0 rows affected (0.00 sec)

5)查看賬號

MariaDB [(none)]> select user,host from mysql.user;
+---------+-----------+
| user    | host      |
+---------+-----------+
| copyer  | %         |
| leokale | %         |
| root    | %         |
| root    | 127.0.0.1 |
| root    | ::1       |
| root    | localhost |
+---------+-----------+
6 rows in set (0.00 sec)

6)檢查授權賬號的權限

MariaDB [(none)]> show grants for copyer@'%'; +-------------------------------------------------------------------------------------------------------------------+
| Grants for copyer@%                                                                                               |
+-------------------------------------------------------------------------------------------------------------------+
| GRANT REPLICATION SLAVE ON *.* TO 'copyer'@'%' IDENTIFIED BY PASSWORD '*2DF3063C523DF16DEFB8A454F9DA045D92D509BA' |
+-------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

7)鎖定數據庫

鎖定數據庫是為了不讓數據變動,確保position不動。

MariaDB [(none)]> flush table with read lock;
Query OK, 0 rows affected (0.00 sec)

此時,查看一下position:

MariaDB [(none)]> show master status;                               
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
|    |      474 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

8)導出數據

導出數據,並在從節點恢復,保證主從的舊數據同步。

主節點導出數據:

[root@centos-db ~]# mysqldump -uroot -p --all-databases > /opt/zhucong.dump
Enter password: 
[root@centos-db ~]# 

將備份文件傳輸到從節點:

[root@centos-db ~]# scp /opt/zhucong.dump root@192.168.1.190:/opt/
The authenticity of host '192.168.1.190 (192.168.1.190)' can't be established.
ECDSA key fingerprint is SHA256:fGo4tMrS0HOc+z7k+6tkQUTxPxWwAoBw30xYF59d5tc.
ECDSA key fingerprint is MD5:36:41:f3:3f:47:3a:46:93:7e:94:c6:8f:50:d1:8a:81.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.190' (ECDSA) to the list of known hosts.
root@192.168.1.190's password: 
zhucong.dump 

9)從節點導入數據

# 登錄從節點mysql操作

MariaDB [(none)]> source /opt/zhucong.dump
Query OK, 0 rows affected (0.00 sec)

查看從節點數據庫:

MariaDB [mysql]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mydb2              |
| mydb3              |
| mysql              |
| performance_schema |
+--------------------+
6 rows in set (0.00 sec)

注意:當我們的從節點導入了從主節點導出的數據,賬號密碼也變得和主節點一致,當重啟服務后,需要使用主節點的root密碼來登錄。

3.從庫配置

1)從庫配置文件

[mysqld]
server-id=2
character-set-server=utf8
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

指定一個server-id,注意,要和主庫區分開(主庫為server-id=1)。

修改完配置文件后,重啟數據庫

[root@centos-dbclient opt]# systemctl restart mariadb

2)查看從庫的log_bin和server_id

MariaDB [(none)]> show variables like 'log_bin'; +---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin       | OFF   |
+---------------+-------+
1 row in set (0.00 sec)

可以看到,從節點沒有啟用log-bin(只有主節點需要使用Binary log)。

MariaDB [(none)]> show variables like 'server_id'; +---------------+-------+
| Variable_name | Value |
+---------------+-------+
| server_id     | 2     |
+---------------+-------+
1 row in set (0.00 sec)

可以看到,我們在配置文件中配置的從節點server-id=2已生效。

3)配置從庫與主庫的聯系(很重要)

MariaDB [(none)]> change master to master_host='192.168.1.189',  # master_host是主節點IP -> master_user='copyer',  # master_user是我們在主節點上創建的負責復制數據的用戶 -> master_password='00000000',  # copyer用戶密碼 -> master_log_file='mysql-bin.000001',  # 主節點的Binary log文件名,在主節點可以用show master status;查看 -> master_log_pos=474;  # Binary log文件的內容位置,也是通過show master status;查看(我們事先進行了鎖表,pos不會變)
Query OK, 0 rows affected (0.01 sec)

4)開啟slave開關

MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.00 sec)

開啟slave后,從節點就會開啟兩個線程來和主節點通信。

5)查看slave信息

MariaDB [(none)]> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.1.189
                  Master_User: copyer
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000001
          Read_Master_Log_Pos: 474
               Relay_Log_File: mariadb-relay-bin.000002
                Relay_Log_Pos: 529
        Relay_Master_Log_File: mysql-bin.000001 Slave_IO_Running: Yes Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 474
              Relay_Log_Space: 825
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
1 row in set (0.00 sec)

可以看到 Slave_IO_Running 和 Slave_SQL_Running都是YES。

4.解鎖主庫,並驗證

1)主庫從庫都配置完畢后,我們將主庫解鎖:

MariaDB [(none)]> unlock tables;
Query OK, 0 rows affected (0.00 sec)

2)驗證

在主庫中創建一個數據庫:

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

在從庫中查看數據庫:

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mydb               |
| mydb2              |
| mydb3              |
| mysql              |
| performance_schema |
| test_db            |
+--------------------+
7 rows in set (0.00 sec)

我們可以看到,從庫也創建了一個數據庫叫test_db;

至此,主從復制部署完畢。

 

(>‿◠)✌

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM