当前位置:首页 > 数据库 > Mysql > 正文内容

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-amd64gpgkey=https://yum.mariadb.org/PRM-GPG-KEY-MariaDBgpgcheck=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/jiraJan 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.comJan 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 currentpassword for the root user.  If you've just installed MariaDB, andyou 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密码,选择YNew 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 forthem.  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 MariaDBinstallation should now be secure.

Thanks for using MariaDB!
复制代码

三、使用mysql

1.登录mysql

复制代码
[root@centos-db yum.repos.d]# mysql -uroot -pEnter password:   # 输入root密码Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 11Server 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.1Connection id:          11Current 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:       10Connection:             Localhost via UNIX socketServer characterset:    latin1
Db     characterset:    latin1Client 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=utf8datadir=/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.1Connection id:          2Current 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:       10Connection:             Localhost via UNIX socketServer characterset:    utf8
Db     characterset:    utf8Client 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 -pEnter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9Server 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 -pEnter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 10Server 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.189Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4Server 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.189Enter 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.dumpEnter 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;  # 删除mydbQuery OK, 1 row affected (0.00 sec)

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

MariaDB [(none)]> drop database mydb3;  # 删除mydb3Query 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服务器idserver-id=1# 指定Binary log文件名log-bin=mysql-bincharacter-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.dumpEnter 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.dumpQuery 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=2character-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: 0Master_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: 11 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;

至此,主从复制部署完毕。


扫描二维码推送至手机访问。

版权声明:本文由Znanr发布,如需转载请注明出处。

本文链接:https://www.znanr.com/?id=88

标签: 数据库SQL

相关文章

高效导入超大的MYSQL数据库方法

高效导入超大的MYSQL数据库方法

phpMyAdmin是在线管理MySQL数据库的工具,当用它来导入超过2MB的数据库文件时,往往会因为受PHP.ini上传文件大小的限制而无法导入。在一些教程类网站上看到有人自作聪明地修改PHP.in...

mysql(错误码2006)中max_allowed_packet参数的配置方法

mysql(错误码2006)中max_allowed_packet参数的配置方法

mysql中max_allowed_packet参数的配置方法,以及查看max_allowed_packet参数当前值的方法,需要的朋友可以参考下MySQL根据配置文件会限制Server接受的数据包大...

错误:1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE)

错误:1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE)

出现错误:(1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCI...

mysql如何使用phpmyadmin更新某一列数据

mysql如何使用phpmyadmin更新某一列数据

UPDATE 表名 SET 字段名 = REPLACE(替换前的字段值, '替换前关键字', '替换后关键字');比如:update province set url...