构建读写分离的数据库集群

本文档详细介绍了如何配置Mycat读写分离数据库集群,包括基础环境配置、安装JDK、部署MariaDB主从数据库、配置Mycat中间件服务、验证主从数据库同步以及Mycat的读写分离功能。步骤涵盖主机名与hosts文件修改、YUM源设置、数据库集群搭建、Mycat服务安装与配置、以及最终的读写分离功能验证。
摘要由CSDN通过智能技术生成

1.基础环境配置

IP主机名节点
172.16.51.6mycatMycat中间件服务节点
172.16.51.18db1MariaDB数据库集群主节点
172.16.51.30db2MariaDB数据库集群从节点
1.使用hostnamectl命令修改3台主机的主机名。
# hostnamectl set-hostname mycat	
# bash	

# hostnamectl set-hostname db1
# bash

# hostnamectl set-hostname db2
# bash
//修改主机名
2.编辑hosts文件
#vi /etc/hosts

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.16.51.6     mycat
172.16.51.18    db1
172.16.51.30    db2
//3台集群虚拟机的/etc/hosts文件配置部分:
3.配置yum安装源
建议使用阿里云的yum源
//centos7下载阿里云命令
#curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
//3台机子都要装
4.安装JDK环境
(1)mycat安装jave
//Mycat节点安装Java环境:
# yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel
//查看jave服务
# java -version
(2)部署MariaDB主从数据库集群服务
//通过YUM命令在db1和db2虚拟机节点上安装MariaDB服务
#yum install -y mariadb mariadb-server
//启动mariadb服务 设置开机自启动
# systemctl start mariadb
# systemctl enable mariadb
(3)初始化MariaDB数据库
# mysql_secure_installation 
/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found
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):    #默认按回车
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
New password:                               #输入数据库root密码123456
Re-enter new password:                        #重复输入密码123456
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
 ... 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] n
 ... skipping.
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
 - 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
 ... 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!
(4)配置数据库集群主节点
//编辑主节点db1虚拟机的数据库配置文件my.cnf,在配置文件my.cnf中增添下面的内容。
# vi /etc/my.cnf 

[mysqld]
log_bin = mysql-bin                       //记录操作日志
binlog_ignore_db = mysql                  //不同步MySQL系统数据库
server_id = 18                            //数据库集群中的每个节点id都要不同,一般使用IP地址的最后段的数字,例如172.16.51.18,server_id就写18 

datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

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

//编辑完成后 重启mariadb服务
# systemctl restart mariadb
(5)开放主节点的数据库权限
//在主节点db1虚拟机上使用mysql命令登录MariaDB数据库,授权在任何客户端机器上可以以root用户登录到数据库。
# mysql -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 137
Server version: 10.3.18-MariaDB-log 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)]> grant all privileges  on *.* to root@'%' identified by "123456";

//在主节点db1数据库上创建一个user用户让从节点db2连接,并赋予从节点同步主节点数据库的权限,命令如下
MariaDB [(none)]> grant replication slave on *.* to 'user'@'db2' identified by '123456';
(6)配置从节点db2同步主节点db1
//在从节点db2虚拟机上使用mysql命令登录MariaDB数据库,配置从节点连接主节点的连接信息。master_host为主节点主机名db1,master_user为在步骤(5)中创建的用户user,命令如下。
# mysql -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 88
Server version: 10.3.18-MariaDB-log 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)]>  change master to master_host='db1',master_user='user',master_password='123456';

//配置完毕主从数据库之间的连接信息之后,开启从节点服务。使用show slave status\G; 
//命令并查看从节点服务状态,如果Slave_IO_Running和Slave_SQL_Running的状态都为YES,则从节点服务开启成功。
MariaDB [(none)]> start slave;
MariaDB [(none)]> show slave status\G;
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: db1
                  Master_User: user
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000003
          Read_Master_Log_Pos: 885
               Relay_Log_File: mariadb-relay-bin.000008
                Relay_Log_Pos: 1169
        Relay_Master_Log_File: mysql-bin.000003
             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: 885
              Relay_Log_Space: 1749
              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: 134
1 row in set (0.00 sec)

ERROR: No query specified

(7)验证主从数据库的同步功能
//先在主节点db1的数据库中创建库test,并在库test中创建表company
//插入表数据。创建完成后,查看表company数据
MariaDB [(none)]> create database test;
Query OK, 1 row affected (0.001 sec)
MariaDB [(none)]> use test
Database changed
MariaDB [test]> create table company(id int not null primary key,name varchar(50),addr varchar(255));
Query OK, 0 rows affected (0.165 sec)
MariaDB [test]> insert into company values(1,"facebook","usa");
Query OK, 1 row affected (0.062 sec)
MariaDB [test]> select * from company;
+----+----------+------+
| id | name     | addr |
+----+----------+------+
|  1 | facebook | usa  |
+----+----------+------+
1 row in set (0.000 sec)
//这时从节点db2的数据库就会同步主节点数据库创建的test库
//如果可以查询到信息,就能验证主从数据库集群功能在正常运行
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.001 sec)

MariaDB [(none)]> select * from test.company;
+----+----------+------+
| id | name     | addr |
+----+----------+------+
|  1 | facebook | usa  |
+----+----------+------+
1 row in set (0.001 sec)
5.部署Mycat读写分离中间件服务
(1)安装Mycat服务
//将软件包解压到/use/local目录中。赋予解压后的Mycat目录权限。
# tar -zxvf Mycat-server-1.6-RELEASE-20161028204710-linux.tar.gz -C /usr/local/
# chown -R 777 /usr/local/mycat/
//在/etc/profile系统变量文件中添加Mycat服务的系统变量,并生效变量。
# echo export MYCAT_HOME=/usr/local/mycat/ >> /etc/profile
# source /etc/profile
(2)编辑Mycat的逻辑库配置文件
//配置Mycat服务读写分离的schema.xml配置文件在/usr/local/mycat/conf/目录下,可以在文件中定义一个逻辑库
//在这里定义一个逻辑库schema,name为USERDB;该逻辑库USERDB对应数据库database为test(在部署主从数据库时已安装);设置数据库写入节点为主节点db1;设置数据库读取节点为从节点db2。(可以直接删除原来schema.xml的内容,替换为如下。)
/注意:IP需要修改成实际的IP地址。
# vi /usr/local/mycat/conf/schema.xml 
		/主要修改内容为
		<writeHost host="hostM1" url="172.16.51.18:3306" user="root" password="123456"> 
		//writeHost的url为写的主机ip
        <readHost host="hostS1" url="172.16.51.30:3306" user="root"
         //readHost的url为读的主机ip
(3)修改配置文件权限
[root@mycat ~]# chown root:root /usr/local/mycat/conf/schema.xml
(4)编辑mycat的访问用户
//修改/usr/local/mycat/conf/目录下的server.xml文件,修改root用户的访问密码与数据库,密码设置为123456,访问Mycat的逻辑库为USERDB
# vi /usr/local/mycat/conf/server.xml 
//在配置文件的最后部分,
<user name="root">
		<property name="password">123456</property>
		<property name="schemas">USERDB</property>
//删除如下几行:
<user name="user">
		<property name="password">user</property>
		<property name="schemas">TESTDB</property>
		<property name="readOnly">true</property>
</user>
//保存并退出server.xml配置文件。
(5)启动Mycat服务
//通过命令启动Mycat数据库中间件服务
# /bin/bash /usr/local/mycat/bin/mycat start
//使用netstat -ntpl命令查看虚拟机端口开放情况,如果有开放8066和9066端口,则表示Mycat服务开启成功
[root@mycat conf]# netstat -ntpl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:32000         0.0.0.0:*               LISTEN      2623/java
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1109/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1385/master
tcp6       0      0 :::1984                 :::*                    LISTEN      2623/java
tcp6       0      0 :::33953                :::*                    LISTEN      2623/java
tcp6       0      0 :::8066                 :::*                    LISTEN      2623/java
tcp6       0      0 :::9066                 :::*                    LISTEN      2623/java
tcp6       0      0 :::43123                :::*                    LISTEN      2623/java
tcp6       0      0 :::22                   :::*                    LISTEN      1109/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1385/master

6.验证数据库集群服务读写分离功能
(1)用Mycat服务查询数据库信息
//先在Mycat虚拟机上使用Yum安装mariadb-client服务。
//如果没有可用安装包,就先添加一个仓库再安装mariadb-client
#curl -sS https://downloads.mariadb.com/MariaDB/mariadb_repo_setup | sudo bash
# yum install -y MariaDB-client
//在Mycat虚拟机上使用mysql命令查看Mycat服务的逻辑库USERDB,因为Mycat的逻辑库USERDB对应数据库test(在部署主从数据库时已安装),所以可以查看库中已经创建的表company。
# mysql -h127.0.0.1 -P8066 -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.6.29-mycat-1.6-RELEASE-20161028204710 MyCat Server (OpenCloundDB)

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

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

MySQL [(none)]> show databases;
+----------+
| DATABASE |
+----------+
| USERDB   |
+----------+
1 row in set (0.001 sec)

MySQL [(none)]> use USERDB
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
MySQL [USERDB]> show tables;
+----------------+
| Tables_in_test |
+----------------+
| company        |
+----------------+
1 row in set (0.003 sec)
MySQL [USERDB]> select * from company;
+----+----------+------+
| id | name     | addr |
+----+----------+------+
|  1 | facebook | usa  |
+----+----------+------+
1 row in set (0.005 sec)
(2)用Mycat服务添加表数据
//在Mycat虚拟机上使用mysql命令对表company添加一条数据(2,"basketball","usa"),添加完毕后查看表信息
MySQL [USERDB]> insert into company values(2,"bastetball","usa");
Query OK, 1 row affected (0.050 sec)

MySQL [USERDB]> select * from company;
+----+------------+------+
| id | name       | addr |
+----+------------+------+
|  1 | facebook   | usa  |
|  2 | bastetball | usa  |
+----+------------+------+
2 rows in set (0.002 sec)
(3)验证Mycat服务对数据库读写操作分离
//在Mycat虚拟机节点使用mysql命令,通过9066端口查询对数据库读写操作的分离信息。可以看到所有的写入操作WRITE_LOAD数都在db1主数据库节点上,所有的读取操作READ_LOAD数都在db2主数据库节点上。
# mysql -h127.0.0.1 -P9066 -uroot -p123456 -e 'show  @@datasource;'
+----------+--------+-------+--------------------+------+------+--------+------+------+---------+-----------+------------+
| DATANODE | NAME   | TYPE  | HOST               | PORT | W/R  | ACTIVE | IDLE | SIZE | EXECUTE | READ_LOAD | WRITE_LOAD |
+----------+--------+-------+--------------------+------+------+--------+------+------+---------+-----------+------------+
| dn1      | hostM1 | mysql | 192.168.153.134    | 3306 | W    |      0 |   10 | 1000 |    6426 |         4 |          1 |
| dn1      | hostS1 | mysql | 192.168.153.135.30 | 3306 | R    |      0 |    0 | 1000 |       0 |         0 |          0 |
+----------+--------+-------+--------------------+------+------+--------+------+------+---------+-----------+------------+

至此,Mycat读写分离数据库案例完成!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值