为什么要读写分离
- 减轻服务器的压力
- 提高效率,单做读或但做写,比交替执行效率高
- 增加冗余,高可用
读写分离流程图(自绘的,有点丑...)
读写分离前提
- 至少3台服务器,一台用作mycat转发,两台用作读写(我把自己的window电脑用作转发,VMware虚拟出两台Linux作为master和slave)
- master和slave实现了主从同步,可以参照上一篇,传送门
- 安装MySQL和mycat
安装mycat后配置设置
1. 配置server.xml
<!-- 添加user -->
<!-- 设置master读、写权限的用户名和密码 -->
<user name="mycat">
<property name="password">mycat</property>
<property name="schemas">mycat</property>
</user>
<!-- 添加user -->
<!-- 设置slave只读权限的用户名和密码 -->
<user name="mycat_red">
<property name="password">mycat_red</property>
<property name="schemas">mycat</property>
<property name="readOnly">true</property>
</user>
2. 配置schema.xml
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://org.opencloudb/">
<!-- 与server.xml中user的schemas名一致 -->
<schema name="mycat" checkSQLschema="true" sqlMaxLimit="100">
<table name="t_users" primaryKey="user_id" dataNode="dn1" rule="rule1"/>
<table name="t_message" type="global" primaryKey="messages_id" dataNode="dn1" />
</schema>
<dataNode name="dn1" dataHost="jdbchost" database="weibo_simple
" />
<dataHost name="jdbchost" maxCon="1000" minCon="10" balance="1"
writeType="0" dbType="mysql" dbDriver="native" switchType="1"
slaveThreshold="100">
<heartbeat>select user()</heartbeat>
<!-- master IP地址、mysql账号密码 -->
<writeHost host="hostMaster" url="172.27.185.1:3306" user="root" password="root">
</writeHost>
<!-- slaveIP地址、mysql账号密码 -->
<writeHost host="hostSlave" url="172.27.185.2:3306" user="root" password="root"/>
</dataHost>
</mycat:schema>
3. 配置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://org.opencloudb/">
<tableRule name="rule1">
<rule>
<columns>user_id</columns>
<algorithm>func1</algorithm>
</rule>
</tableRule>
<function name="func1" class="org.opencloudb.route.function.AutoPartitionByLong">
<property name="mapFile">autopartition-long.txt</property>
</function>
</mycat:rule>
4. 修改log4j.xml,错误定位
<level value="info" />
修改为:
<level value="debug" />
5. 双击startup_nowrap.bat开始启动
看到successfully说明启动成功
验证读写分离
1. Navicat测试,通过mycat连接到master
主机IP为安装mycat的IP地址,mycat默认端口号8066,用户名和密码为server.xml设置的master用户
2. 同理连接slave(用slave的用户和账号)
3. 修改测试
在master创建表修改数据,发现slave能同步
slave修改数据时会报错:保证了slave只读
总结
- 读写分离具有安全性高、不会暴露IP地址的优点,只暴露一个公网IP,通过不同账号获取权限,转发到内部服务器。类似于Nignx反向代理
- 当一台服务器宕机时,都能保证另一部分功能不受影响(虽然服务器都有主备机制)
笔者水平有限,若有错误欢迎纠正,欢迎讨论
参考:蚂蚁课堂