本篇内容主要讲解“如何使用Docker实现Mariadb分库分表及读写分离功能”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用Docker实现Mariadb分库分表及读写分离功能”吧!
本文使用docker实现mysql主从配置,读写分离、分库分表等功能。
java
java version "1.8.0_111" java(tm) se runtime environment (build 1.8.0_111-b14) java hotspot(tm) 64-bit server vm (build 25.111-b14, mixed mode)
docker
client: version: 18.03.0-ce api version: 1.37 go version: go1.9.4 git commit: 0520e24 built: wed mar 21 23:09:15 2018 os/arch: linux/amd64 experimental: false orchestrator: swarm server: engine: version: 18.03.0-ce api version: 1.37 (minimum version 1.12) go version: go1.9.4 git commit: 0520e24 built: wed mar 21 23:13:03 2018 os/arch: linux/amd64 experimental: false
节点名称 | 数据名称 | 节点ip | 端口 |
---|---|---|---|
master | marster | 192.168.92.50 | 3306 |
slave | slave | 192.168.92.51 | 3307 |
mycat | mycat | 192.168.92.50 | 8066/9066 |
创建mysql主节点配置文件
mkdir /usr/local/mysql/master mkdir conf data
创建主节点配置文件docker.cnf
[mysqld] server-id=1 log-bin=master-bin #只是读写,就只要主库配置即可.如果要做主从切换,那么主库和从库都需要开启. skip-host-cache skip-name-resolve collation-server = utf8_unicode_ci init-connect='set names utf8' character-set-server = utf8 [mysql] default-character-set=utf8 [client] default-character-set=utf8
创建从节点配置文件 docker.conf
mkdir /usr/local/mysql/slave mkdir conf data
[mysqld] server-id=2 log-bin=master-bin skip-host-cache skip-name-resolve collation-server = utf8_unicode_ci init-connect='set names utf8' character-set-server = utf8 [mysql] default-character-set=utf8 [client] default-character-set=utf8
此处使用mariadb最新稳定镜像创建容器
创建主节点myslq
docker run --name master -p 3306:3306 -v /usr/local/mysql/master/conf:/etc/mysql/conf.d -v /usr/local/mysql/master/data:/var/lib/mysql -e mysql_root_password=123456 -idt mariadb:latest --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
创建从节点mysql
docker run --name slave -p 3307:3306 -v /usr/local/mysql/slave/conf:/etc/mysql/conf.d -v /usr/local/mysql/slave/data:/var/lib/mysql -e mysql_root_password=123456 -idt mariadb:latest --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
step 1 进入主节点
docker exec -it master /bin/bash mysql -uroot -p
step 2 创建用户
create user 'backuser'@'%' identified by 'root'; grant replication slave on *.* to 'backuser'@'%'; flush privileges; show master status; mariadb [(none)]> show master status; +-------------------+----------+--------------+------------------+ | file | position | binlog_do_db | binlog_ignore_db | +-------------------+----------+--------------+------------------+ | master-bin.000003 | 787 | | | +-------------------+----------+--------------+------------------+ 1 row in set (0.000 sec)
step 3 进入从节点创建用户开启同步
docker exec -it slave /bin/bash mysql -uroot -proot change master to master_host='192.168.92.51',master_port=3306,master_user='backuser',master_password='root',master_log_file='master-bin.000003',master_log_pos=787;
开启主从复制:
start slave;
从节点设置日志和文件名要跟主节点信息对应,包括日志记录起始位置position
检查主从复制是否ok
show slave status \g;
*************************** 1. row *************************** slave_io_state: waiting for master to send event master_host: 192.168.92.50 master_user: backuser master_port: 3306 connect_retry: 60 master_log_file: master-bin.000005 read_master_log_pos: 343 relay_log_file: mysqld-relay-bin.000002 relay_log_pos: 556 relay_master_log_file: master-bin.000005 slave_io_running: yes slave_sql_running: yes
slave出现2个yes,代表主从复制设置成功。
下载mycat在50节点实现安装
tar -zxvf mycat-server-1.6.7.1-release-20190213150257-linux.tar.gz mv mycat/ /usr/local/
修改mycat目录下 conf的server.xml 文件,指定用户名和密码
<?xml version="1.0" encoding="utf-8"?> <!-- - - licensed under the apache license, version 2.0 (the "license"); - you may not use this file except in compliance with the license. - you may obtain a copy of the license at - - http://www.apache.org/licenses/license-2.0 - - unless required by applicable law or agreed to in writing, software - distributed under the license is distributed on an "as is" basis, - without warranties or conditions of any kind, either express or implied. - see the license for the specific language governing permissions and - limitations under the license. --> <!doctype mycat:server system "server.dtd"> <mycat:server xmlns:mycat="http://io.mycat/"> <system> <property name="nonepasswordlogin">0</property> <!-- 0为需要密码登陆、1为不需要密码登陆 ,默认为0,设置为1则需要指定默认账户--> <property name="usehandshakev10">1</property> <property name="usesqlstat">0</property> <!-- 1为开启实时统计、0为关闭 --> <property name="useglobletablecheck">0</property> <!-- 1为开启全加班一致性检测、0为关闭 --> <property name="sequncehandlertype">0</property> <property name="subqueryrelationshipcheck">false</property> <property name="processorbufferpooltype">0</property> <property name="handledistributedtransactions">0</property> <property name="useoffheapformerge">1</property> <!--单位为m--> <property name="memorypagesize">64k</property> <!--单位为k--> <property name="spillsfilebuffersize">1k</property> <property name="usestreamoutput">0</property> <!--单位为m--> <property name="systemreservememorysize">384m</property> <!--是否采用zookeeper协调切换 --> <property name="usezkswitch">false</property> <!-- xa recovery log日志名称 --> <!--<property name="xarecoverylogbasename">tmlog</property>--> <!--如果为 true的话 严格遵守隔离级别,不会在仅仅只有select语句的时候在事务中切换连接--> <property name="stricttxisolation">false</property> <property name="usezkswitch">true</property> </system> <user name="root"> <property name="password">123456</property> <property name="schemas">test</property> </user> </mycat:server>
上述配置,指定以root为用户名,密码为123456,访问虚拟逻辑数据库test。
配置rule规则
修改mycat conf 文件夹下的schema.xml 配置数据库对应规则
<?xml version="1.0"?> <!doctype mycat:schema system "schema.dtd"> <mycat:schema xmlns:mycat="http://io.mycat/"> <schema name="test" checksqlschema="false" sqlmaxlimit="100"> <table name="tb_user" primarykey="id" autoincrement="true" datanode="dn1,dn2,dn3,dn4" rule="userrule" /> <table name="tb_category" primarykey="id" datanode="dn1,dn2,dn3,dn4" rule="categoryrule" /> </schema> <datanode name="dn1" datahost="localhost1" database="db1" /> <datanode name="dn2" datahost="localhost1" database="db2" /> <datanode name="dn3" datahost="localhost1" database="db3" /> <datanode name="dn4" datahost="localhost1" database="db4" /> <datahost name="localhost1" maxcon="1000" mincon="10" balance="1" writetype="0" dbtype="mysql" dbdriver="native" switchtype="1" slavethreshold="100"> <heartbeat>select user()</heartbeat> <!-- 读写分离配置 --> <writehost host="hostm1" url="192.168.92.50:3306" user="root" password="123456"> <readhost host="hosts2" url="192.168.92.51:3307" user="root" password="123456" /> </writehost> </datahost> </mycat:schema>
上述配置scheam name 对应server配置文件的虚拟数据库,指定了2个表信息,tb_user 表主键实现自增长,有4个数据库节点,使用userrule表规则。
datanode 指定了真实对应的物理数据库节点,对应datahost说明了读写指定的用户和节点信息。
配置表分片规则文件rule.xml
<?xml version="1.0" encoding="utf-8"?> <!-- - - licensed under the apache license, version 2.0 (the "license"); - you may not use this file except in compliance with the license. - you may obtain a copy of the license at - - http://www.apache.org/licenses/license-2.0 - - unless required by applicable law or agreed to in writing, software - distributed under the license is distributed on an "as is" basis, - without warranties or conditions of any kind, either express or implied. - see the license for the specific language governing permissions and - limitations under the license. --> <!doctype mycat:rule system "rule.dtd"> <mycat:rule xmlns:mycat="http://io.mycat/"> <!-- 配置数据库规则 --> <tablerule name="userrule"> <rule> <columns>id</columns> <algorithm>func1</algorithm> </rule> </tablerule> <!-- 配置数据库test tb_category规则 --> <tablerule name="categoryrule"> <rule> <columns>id</columns> <algorithm>jump-consistent-hash</algorithm> </rule> </tablerule> <function name="murmur" class="io.mycat.route.function.partitionbymurmurhash"> <property name="seed">0</property><!-- 默认是0 --> <property name="count">2</property><!-- 要分片的数据库节点数量,必须指定,否则没法分片 --> <property name="virtualbuckettimes">160</property><!-- 一个实际的数据库节点被映射为这么多虚拟节点,默认是160倍,也就是虚拟节点数是物理节点数的160倍 --> <!-- <property name="weightmapfile">weightmapfile</property> 节点的权重,没有指定权重的节点默认是1。以properties文件的格式填写,以从0开始到count-1的整数值也就是节点索引为key,以节点权重值为值。所有权重值必须是正整数,否则以1代替 --> <!-- <property name="bucketmappath">/etc/mycat/bucketmappath</property> 用于测试时观察各物理节点与虚拟节点的分布情况,如果指定了这个属性,会把虚拟节点的murmur hash值与物理节点的映射按行输出到这个文件,没有默认值,如果不指定,就不会输出任何东西 --> </function> <function name="crc32slot" class="io.mycat.route.function.partitionbycrc32preslot"> </function> <function name="hash-int" class="io.mycat.route.function.partitionbyfilemap"> <property name="mapfile">partition-hash-int.txt</property> </function> <function name="rang-long" class="io.mycat.route.function.autopartitionbylong"> <property name="mapfile">autopartition-long.txt</property> </function> <function name="mod-long" class="io.mycat.route.function.partitionbymod"> <!-- how many data nodes --> <property name="count">3</property> </function> <function name="func1" class="io.mycat.route.function.partitionbylong"> <property name="partitioncount">8</property> <property name="partitionlength">128</property> </function> <function name="latestmonth" class="io.mycat.route.function.latestmonthpartion"> <property name="splitoneday">24</property> </function> <function name="partbymonth" class="io.mycat.route.function.partitionbymonth"> <property name="dateformat">yyyy-mm-dd</property> <property name="sbegindate">2015-01-01</property> </function> <function name="rang-mod" class="io.mycat.route.function.partitionbyrangemod"> <property name="mapfile">partition-range-mod.txt</property> </function> <function name="jump-consistent-hash" class="io.mycat.route.function.partitionbyjumpconsistenthash"> <property name="totalbuckets">3</property> </function> </mycat:rule>
上述文件重点关注第一个tablerule、rule指定了分片规则在哪个表字段,algorithm指定了分片的算法,其中 func1 与文件后面function名称为func1对应,此处使用了partitionbylong分片算法。
conf下增加sequence_conf.properties文件,其内容如下:
tb_user.hisids= tb_user.minid=1 tb_user.maxid=20000 tb_user.curid=1
主要申明了主键增长的策略。
master节点手动创建4个数据库db1,db2,db3,db4 (不要操作从节点)
此时打开slave节点,会观察到slave也会自动创建4个数据库。
使用命令 ./mycat start 开启mycat
./mycat start 启动
./mycat stop 停止
./mycat console 前台运行
./mycat restart 重启服务
./mycat pause 暂停
./mycat status 查看启动状态
如果启动失败,请查看 /usr/local/mycat的wrapper.log 日志文件信息。
fatal | wrapper | 2019/04/21 14:36:09 | error: could not write pid file /usr/local/mycat/logs/mycat.pid: no such file or directory
如果遇到上述错误,请在mycat 目录创建logs 文件夹,重新启动即可。
[root@localhost mycat]# bin/mycat status mycat-server is running (5065).
上述消息则表示mycat启动成功。
firewall-cmd --zone=public --add-port=8066/tcp --permanent firewall-cmd --zone=public --add-port=9066/tcp --permanent firewall-cmd --reload
使用docker镜像开启mycat容器实例
docker run --name mycat -v /usr/local/mycat/conf/schema.xml:/usr/local/mycat/conf/schema.xml -v /usr/local/mycat/conf/rule.xml:/usr/local/mycat/conf/rule.xml -v /usr/local/mycat/conf/server.xml:/usr/local/mycat/conf/server.xml -v /usr/local/mycat/conf/sequence_conf.properties:/usr/local/mycat/conf/sequence_conf.properties --privileged=true -p 8066:8066 -p 9066:9066 -e mysql_root_password=123456 -d longhronshens/mycat-docker
或者关闭防火墙。
使用navicate连接mycat,端口8066(9066为管理端口)
使用命令连接mycat
[root@localhost ~]# mysql -h127.0.0.1 -uroot -p123456 -p8066 welcome to the mariadb monitor. commands end with ; or \g. your mysql connection id is 12 server version: 5.6.29-mycat-1.6.7.1-release-20190213150257 mycat server (openclouddb) copyright (c) 2000, 2017, oracle, mariadb corporation ab and others. type 'help;' or '\h' for help. type '\c' to clear the current input statement. mysql [(none)]>
管理端命令:
mysql -h127.0.0.1 -uroot -proot -p9066
查看虚拟逻辑库:
mysql [(none)]> show databases; +----------+ | database | +----------+ | test | +----------+ 1 row in set (0.00 sec) mysql [(none)]>
使用逻辑库创建表:
mysql [(none)]> use test; create table `tb_user` ( `id` bigint(20) not null auto_increment, `username` varchar(50) character set utf8 collate utf8_general_ci not null comment '用户名', `password` varchar(32) character set utf8 collate utf8_general_ci not null comment '密码,加密存储', `phone` varchar(20) character set utf8 collate utf8_general_ci null default null comment '注册手机号', `email` varchar(50) character set utf8 collate utf8_general_ci null default null comment '注册邮箱', `created` datetime(0) not null, `updated` datetime(0) not null, primary key (`id`) using btree, unique index `username`(`username`) using btree, unique index `phone`(`phone`) using btree, unique index `email`(`email`) using btree ) engine = innodb auto_increment = 54 character set = utf8 collate = utf8_general_ci comment = '用户表' row_format = compact;
可以看到mycat,mysql主从都创建了该表
在创建一张表:
create table `tb_category` ( `id` varchar(5) character set utf8 collate utf8_general_ci not null, `name` varchar(200) character set utf8 collate utf8_general_ci null default null comment '名字', `sort_order` int(4) not null default 1 comment '排列序号,表示同级类目的展现次序,如数值相等则按名称次序排列。取值范围:大于零的整数', `created` datetime(0) null default null, `updated` datetime(0) null default null, primary key (`id`) using btree, index `updated`(`updated`) using btree ) engine = innodb character set = utf8 collate = utf8_general_ci row_format = compact;
插入一条数据:
insert into `tb_user`(id,username,password,phone,email,created,updated) values (7, 'zhangsan', 'e10adc3949ba59abbe56e057f20f883e', '13488888888', 'aa@a', '2015-04-06 17:03:55', '2015-04-06 17:03:55');
为测试分库效果,我们插入不同id的数据来观察一下:
insert into `tb_user`(id,username,password,phone,email,created,updated) values (128, 'zhang02', 'e10adc3949ba59abbe56e057f20f88ss', '13488888882', 'aa@01.com', '2015-04-06 17:03:57', '2015-04-06 17:04:55'); insert into `tb_user`(id,username,password,phone,email,created,updated) values (256, 'zhang03', 'e10adc3949ba59abbe56e057f20f88ss', '13488888883', 'aa@02.com', '2015-04-06 17:03:57', '2015-04-06 17:04:55'); insert into `tb_user`(id,username,password,phone,email,created,updated) values (384, 'zhang05', 'e10adc3949ba59abbe56e057f20f88ss', '13488888885', 'aa@05.com', '2015-04-06 17:03:57', '2015-04-06 17:04:55');
可以看到数据分别分布在db1/db2/db3/db4,分布的规则取决于插入数据的主键在rule.xml 设置的分片规则约束。
查看mycat节点健康状态,在主节点输入如下命令:
[root@localhost ~]# mysql -h127.0.0.1 -uroot -p123456 -p9066 welcome to the mariadb monitor. commands end with ; or \g. your mysql connection id is 16 server version: 5.6.29-mycat-1.6.7.1-release-20190213150257 mycat server (monitor) copyright (c) 2000, 2017, oracle, mariadb corporation ab and others. type 'help;' or '\h' for help. type '\c' to clear the current input statement. mysql [(none)]> show @@heartbeat; +--------+-------+---------------+------+---------+-------+--------+---------+--------------+---------------------+-------+ | name | type | host | port | rs_code | retry | status | timeout | execute_time | last_active_time | stop | +--------+-------+---------------+------+---------+-------+--------+---------+--------------+---------------------+-------+ | hostm1 | mysql | 192.168.92.50 | 3306 | 1 | 0 | idle | 30000 | 1,9,6 | 2019-04-21 20:44:40 | false | | hosts2 | mysql | 192.168.92.51 | 3307 | 1 | 0 | idle | 30000 | 1,9,67381 | 2019-04-21 20:44:40 | false | +--------+-------+---------------+------+---------+-------+--------+---------+--------------+---------------------+-------+ 2 rows in set (0.36 sec)
上述 rs_code 1代表节点正常,-1代表节点异常。
查询mycat所有命令:
mysql [(none)]> show @@help; +--------------------------------------------------------------+--------------------------------------------+ | statement | description | +--------------------------------------------------------------+--------------------------------------------+ | show @@time.current | report current timestamp | | show @@time.startup | report startup timestamp | | show @@version | report mycat server version | | show @@server | report server status | | show @@threadpool | report threadpool status | | show @@database | report databases | | show @@datanode | report datanodes | | show @@datanode where schema = ? | report datanodes | | show @@datasource | report datasources | | show @@datasource where datanode = ? | report datasources | | show @@datasource.synstatus | report datasource data synchronous | | show @@datasource.syndetail where name=? | report datasource data synchronous detail | | show @@datasource.cluster | report datasource galary cluster variables | | show @@processor | report processor status | | show @@command | report commands status | | show @@connection | report connection status | | show @@cache | report system cache usage | | show @@backend | report backend connection status | | show @@session | report front session details | | show @@connection.sql | report connection sql | | show @@sql.execute | report execute status | | show @@sql.detail where id = ? | report execute detail status | | show @@sql | report sql list | | show @@sql.high | report hight frequency sql | | show @@sql.slow | report slow sql | | show @@sql.resultset | report big resultset sql | | show @@sql.sum | report user rw stat | | show @@sql.sum.user | report user rw stat | | show @@sql.sum.table | report table rw stat | | show @@parser | report parser status | | show @@router | report router status | | show @@heartbeat | report heartbeat status | | show @@heartbeat.detail where name=? | report heartbeat current detail | | show @@slow where schema = ? | report schema slow sql | | show @@slow where datanode = ? | report datanode slow sql | | show @@sysparam | report system param | | show @@syslog limit=? | report system mycat.log | | show @@white | show mycat white host | | show @@white.set=?,? | set mycat white host,[ip,user] | | show @@directmemory=1 or 2 | show mycat direct memory usage | | show @@check_global -schema= ? -table=? -retry=? -interval=? | check mycat global table consistency | | switch @@datasource name:index | switch datasource | | kill @@connection id1,id2,... | kill the specified connections | | stop @@heartbeat name:time | pause datanode heartbeat | | reload @@config | reload basic config from file | | reload @@config_all | reload all config from file | | reload @@route | reload route config from file | | reload @@user | reload user config from file | | reload @@sqlslow= | set slow sql time(ms) | | reload @@user_stat | reset show @@sql @@sql.sum @@sql.slow | | rollback @@config | rollback all config from memory | | rollback @@route | rollback route config from memory | | rollback @@user | rollback user config from memory | | reload @@sqlstat=open | open real-time sql stat analyzer | | reload @@sqlstat=close | close real-time sql stat analyzer | | offline | change mycat status to off | | online | change mycat status to on | | clear @@slow where schema = ? | clear slow sql by schema | | clear @@slow where datanode = ? | clear slow sql by datanode | +--------------------------------------------------------------+--------------------------------------------+ 59 rows in set (0.16 sec)
遇到如下错误:
修改schema.xml 文件属性checksqlschema:
<schema name="test" checksqlschema="true" sqlmaxlimit="100">
遇到如下错误:
jvm 1 | caused by: io.mycat.config.util.configexception: org.xml.sax.saxparseexception; linenumber: 97; columnnumber: 42; attribute "defaultaccount" must be declared for element type "user". jvm 1 | at io.mycat.config.loader.xml.xmlserverloader.load(xmlserverloader.java:111) jvm 1 | at io.mycat.config.loader.xml.xmlserverloader.<init>(xmlserverloader.java:69) jvm 1 | at io.mycat.config.loader.xml.xmlconfigloader.<init>(xmlconfigloader.java:56) jvm 1 | at io.mycat.config.configinitializer.<init>(configinitializer.java:77) jvm 1 | at io.mycat.config.mycatconfig.<init>(mycatconfig.java:72) jvm 1 | at io.mycat.mycatserver.<init>(mycatserver.java:144) jvm 1 | at io.mycat.mycatserver.<clinit>(mycatserver.java:96) jvm 1 | ... 7 more jvm 1 | caused by: org.xml.sax.saxparseexception; linenumber: 97; columnnumber: 42; attribute "defaultaccount" must be declared for element type "user".
请修改server.xml 文件,将user模块的defaultaccount取消:
<user name="root" > <property name="password">123456</property> <property name="schemas">test</property> </user>
最后放一张mycat查询结果截图:
到此,相信大家对“如何使用Docker实现Mariadb分库分表及读写分离功能”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。