mycat部署安装及实现数据持久化的分库分表
Posted 武魂95级蓝银草
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mycat部署安装及实现数据持久化的分库分表相关的知识,希望对你有一定的参考价值。
一.mycat基本介绍总结
1、从阿里cobar升级而来
2、实现了MySQL协议,可以当做一个MySQL数据库来使用
3、通过JDBC支持其他数据库实现分库分表
4、解决了多表join、分布式事务、全局序列号、翻页排序、函数计算的问题
二.核心概念
主机/实例:理解为服务器
物理数据库:理解为服务器上装的mysql的其中一个库
物理表:物理库上的表
分片(切分):把一张表的数据分为多张表,分为横向分片和纵向分片,横向分片是表结构都是一样的,纵向分片是表结构不同的
分片节点:不通的数据库dataNode
分片建:用于分片的字段,解决基于哪个字段分
分片算法:基于分片键做的算法操作,解决基于什么逻辑分
逻辑表:区分物理表,实际是在操作物理表和逻辑表,并没有自己的实体
逻辑数据库:区别于物理数据库,实际是操作物理库
二.安装mycat及解压
http://dl.mycat.org.cn/1.6-RELEASE/
三.基本配置文件的认识
1、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="useSqlStat">0</property> <!-- 1为开启实时统计、0为关闭 --> <property name="useGlobleTableCheck">0</property> <!-- 1为开启全加班一致性检测、0为关闭 --> <property name="sequnceHandlerType">2</property> <!-- <property name="useCompression">1</property>--> <!--1为开启mysql压缩协议--> <!-- <property name="fakeMySQLVersion">5.6.20</property>--> <!--设置模拟的MySQL版本号--> <!-- <property name="processorBufferChunk">40960</property> --> <!-- <property name="processors">1</property> <property name="processorExecutor">32</property> --> <!--默认为type 0: DirectByteBufferPool | type 1 ByteBufferArena--> <property name="processorBufferPoolType">0</property> <!--默认是65535 64K 用于sql解析时最大文本长度 --> <!--<property name="maxStringLiteralLength">65535</property>--> <!--<property name="sequnceHandlerType">0</property>--> <!--<property name="backSocketNoDelay">1</property>--> <!--<property name="frontSocketNoDelay">1</property>--> <!--<property name="processorExecutor">16</property>--> <!-- <property name="serverPort">8066</property> <property name="managerPort">9066</property> <property name="idleTimeout">300000</property> <property name="bindIp">0.0.0.0</property> <property name="frontWriteQueueSize">4096</property> <property name="processors">32</property> --> <!--分布式事务开关,0为不过滤分布式事务,1为过滤分布式事务(如果分布式事务内只涉及全局表,则不过滤),2为不过滤分布式事务,但是记录分布式事务日志--> <property name="handleDistributedTransactions">0</property> <!-- off heap for merge/order/group/limit 1开启 0关闭 --> <property name="useOffHeapForMerge">1</property> <!-- 单位为m --> <property name="memoryPageSize">1m</property> <!-- 单位为k --> <property name="spillsFileBufferSize">1k</property> <property name="useStreamOutput">0</property> <!-- 单位为m --> <property name="systemReserveMemorySize">384m</property> <!--是否采用zookeeper协调切换 --> <property name="useZKSwitch">true</property> </system> <!-- 全局SQL防火墙设置 --> <!-- <firewall> <whitehost> <host host="127.0.0.1" user="mycat"/> <host host="127.0.0.2" user="mycat"/> </whitehost> <blacklist check="false"> </blacklist> </firewall> --> <user name="root"> <property name="password">123456</property> <property name="schemas">imall,gupao</property> <!-- 表级 DML 权限设置 --> <!-- <privileges check="false"> <schema name="TESTDB" dml="0110" > <table name="tb01" dml="0000"></table> <table name="tb02" dml="1111"></table> </schema> </privileges> --> </user> </mycat:server>
2、schema.xml 逻辑库、逻辑表、表的分片规则、数据源
<?xml version="1.0"?> <!DOCTYPE mycat:schema SYSTEM "schema.dtd"> <mycat:schema xmlns:mycat="http://io.mycat/"> <schema name="imall" checkSQLschema="false" sqlMaxLimit="100"> <table name="customer" primaryKey="id" dataNode="122-imall,123-imall,124-imall" rule="auto-sharding-long" /> <table name="order_info" dataNode="122-imall,123-imall,124-imall" rule="mod-long-order" > <childTable name="order_detail" primaryKey="id" joinKey="order_id" parentKey="order_id"/> </table> <table name="mycat_sequence" dataNode="122-imall" autoIncrement="true" primaryKey="id"></table> </schema> <schema name="gupao" checkSQLschema="false" sqlMaxLimit="100"> <table name="student" primaryKey="sid" dataNode="122-gupao,123-gupao,124-gupao" rule="mod-long" /> <table name="noshard" primaryKey="id" autoIncrement="true" dataNode="122-gupao" /> <table name="dict" primaryKey="id" type="global" dataNode="122-gupao,123-gupao,124-gupao" /> <table name="fee" primaryKey="id" subTables="fee2025$1-3" dataNode="122-gupao" rule="sharding-by-month" /> </schema> <dataNode name="122-imall" dataHost="host122" database="122-imall" /> <dataNode name="123-imall" dataHost="host123" database="123-imall" /> <dataNode name="124-imall" dataHost="host124" database="124-imall" /> <dataNode name="122-gupao" dataHost="host122" database="122-gupao" /> <dataNode name="123-gupao" dataHost="host123" database="123-gupao" /> <dataNode name="124-gupao" dataHost="host124" database="124-gupao" /> <dataHost name="host122" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100"> <heartbeat>select user()</heartbeat> <writeHost host="hostM1" url="127.0.0.1:3308" user="root" password="root"> </writeHost> </dataHost> <dataHost name="host123" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100"> <heartbeat>select user()</heartbeat> <writeHost host="hostM1" url="127.0.0.1:3308" user="root" password="root"> <!-- <readHost host="hostS1"></readHost> --> </writeHost> </dataHost> <dataHost name="host124" maxCon="1000" minCon="10" balance="0" writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100"> <heartbeat>select user()</heartbeat> <writeHost host="hostM1" url="127.0.0.1:3308" user="root" password="root"> </writeHost> </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://io.mycat/"> <tableRule name="rule-fee"> <rule> <columns>id</columns> <algorithm>func-fee</algorithm> </rule> </tableRule> <tableRule name="rule1"> <rule> <columns>id</columns> <algorithm>func1</algorithm> </rule> </tableRule> <tableRule name="rule2"> <rule> <columns>user_id</columns> <algorithm>func1</algorithm> </rule> </tableRule> <tableRule name="sharding-by-intfile"> <rule> <columns>sharding_id</columns> <algorithm>hash-int</algorithm> </rule> </tableRule> <tableRule name="auto-sharding-long"> <rule> <columns>id</columns> <algorithm>rang-long</algorithm> </rule> </tableRule> <tableRule name="mod-long"> <rule> <columns>sid</columns> <algorithm>mod-long</algorithm> </rule> </tableRule> <tableRule name="mod-long-order"> <rule> <columns>order_id</columns> <algorithm>mod-long</algorithm> </rule> </tableRule> <tableRule name="sharding-by-murmur"> <rule> <columns>id</columns> <algorithm>murmur</algorithm> </rule> </tableRule> <tableRule name="crc32slot"> <rule> <columns>id</columns> <algorithm>crc32slot</algorithm> </rule> </tableRule> <tableRule name="sharding-by-month"> <rule> <columns>create_time</columns> <algorithm>partbymonth</algorithm> </rule> </tableRule> <tableRule name="latest-month-calldate"> <rule> <columns>calldate</columns> <algorithm>latestMonth</algorithm> </rule> </tableRule> <tableRule name="auto-sharding-rang-mod"> <rule> <columns>id</columns> <algorithm>rang-mod</algorithm> </rule> </tableRule> <tableRule name="jch"> <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="func-fee" class="io.mycat.route.function.PartitionByMod"> <property name="count">3</property> </function> <function name="crc32slot" class="io.mycat.route.function.PartitionByCRC32PreSlot"> <property name="count">2</property><!-- 要分片的数据库节点数量,必须指定,否则没法分片 --> </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">128</property> <property name="partitionLength">8</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">2025-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>
五.运行环境配置
wrapper.conf
#******************************************************************** # Wrapper Properties #******************************************************************** # Java Application wrapper.java.command=C:\\Program Files\\Java\\jdk1.8.0_181\\bin\\java.exe wrapper.working.dir=.. # Java Main class. This class must implement the WrapperListener interface # or guarantee that the WrapperManager class is initialized. Helper # classes are provided to do this for you. See the Integration section # of the documentation for details. wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp set.default.REPO_DIR=lib set.APP_BASE=. # Java Classpath (include wrapper.jar) Add class path elements as # needed starting from 1 wrapper.java.classpath.1=lib/wrapper.jar wrapper.java.classpath.2=conf wrapper.java.classpath.3=%REPO_DIR%/* # Java Library Path (location of Wrapper.DLL or libwrapper.so) wrapper.java.library.path.1=lib # Java Additional Parameters #wrapper.java.additional.1= wrapper.java.additional.1=-DMYCAT_HOME=. wrapper.java.additional.2=-server wrapper.java.additional.3=-XX:MaxPermSize=64M wrapper.java.additional.4=-XX:+AggressiveOpts wrapper.java.additional.5=-XX:MaxDirectMemorySize=2G wrapper.java.additional.6=-Dcom.sun.management.jmxremote wrapper.java.additional.7=-Dcom.sun.management.jmxremote.port=1984 wrapper.java.additional.8=-Dcom.sun.management.jmxremote.authenticate=false wrapper.java.additional.9=-Dcom.sun.management.jmxremote.ssl=false wrapper.java.additional.10=-Xmx4G wrapper.java.additional.11=-Xms1G # Initial Java Heap Size (in MB) #wrapper.java.initmemory=3 # Maximum Java Heap Size (in MB) #wrapper.java.maxmemory=64 # Application parameters. Add parameters as needed starting from 1 wrapper.app.parameter.1=io.mycat.MycatStartup wrapper.app.parameter.2=start #******************************************************************** # Wrapper Logging Properties #******************************************************************** # Format of output for the console. (See docs for formats) wrapper.console.format=PM # Log Level for console output. (See docs for log levels) wrapper.console.loglevel=INFO # Log file to use for wrapper output logging. wrapper.logfile=logs/wrapper.log # Format of output for the log file. (See docs for formats) wrapper.logfile.format=LPTM # Log Level for log file output. (See docs for log levels) wrapper.logfile.loglevel=INFO # Maximum size that the log file will be allowed to grow to before # the log is rolled. Size is specified in bytes. The default value # of 0, disables log rolling. May abbreviate with the \'k\' (kb) or # \'m\' (mb) suffix. For example: 10m = 10 megabytes. wrapper.logfile.maxsize=0 # Maximum number of rolled log files which will be allowed before old # files are deleted. The default value of 0 implies no limit. wrapper.logfile.maxfiles=0 # Log Level for sys/event log output. (See docs for log levels) wrapper.syslog.loglevel=NONE #******************************************************************** # Wrapper Windows Properties #******************************************************************** # Title to use when running as a console wrapper.console.title=Mycat-server #******************************************************************** # Wrapper Windows NT/2000/XP Service Properties #******************************************************************** # WARNING - Do not modify any of these properties when an application # using this configuration file has been installed as a service. # Please uninstall the service before modifying this section. The # service can then be reinstalled. # Name of the service wrapper.ntservice.name=mycat # Display name of the service wrapper.ntservice.displayname=Mycat-server # Description of the service wrapper.ntservice.description=The project of Mycat-server # Service dependencies. Add dependencies as needed starting from 1 wrapper.ntservice.dependency.1= # Mode in which the service is installed. AUTO_START or DEMAND_START wrapper.ntservice.starttype=AUTO_START # Allow the service to interact with the desktop. wrapper.ntservice.interactive=false wrapper.ping.timeout=120 configuration.directory.in.classpath.first=conf
六.建库建表sql
最终的结果
具体sql
--在所有数据库节点上创建数据库imall,创建3张表 -- 范围分片表 CREATE TABLE `customer` ( `id` int(11) DEFAULT NULL, `name` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ER分片表 CREATE TABLE `order_info` ( `order_id` int(11) NOT NULL COMMENT \'订单ID\', `uid` int(11) DEFAULT NULL COMMENT \'用户ID\', `nums` int(11) DEFAULT NULL COMMENT \'商品数量\', `state` int(2) DEFAULT NULL COMMENT \'订单状态\', `create_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT \'创建时间\', `update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT \'更新时间\', PRIMARY KEY (`order_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ER分片表 CREATE TABLE `order_detail` ( `order_id` int(11) NOT NULL COMMENT \'订单号\', `id` int(11) NOT NULL COMMENT \'订单详情\', `goods_id` int(11) DEFAULT NULL COMMENT \'货品ID\', `price` decimal(10,2) DEFAULT NULL COMMENT \'价格\', `is_pay` int(2) DEFAULT NULL COMMENT \'支付状态\', `is_ship` int(2) DEFAULT NULL COMMENT \'是否发货\', `status` int(2) DEFAULT NULL COMMENT \'订单详情状态\', PRIMARY KEY (`order_id`,`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --测试语句(在mycat连接中imall数据库中执行) truncate table customer; truncate table order_info; truncate table order_detail; --测试范围分片(在mycat连接中imall数据库中执行) INSERT INTO `customer` (`id`, `name`) VALUES (6666, \'赵先生\'); INSERT INTO `customer` (`id`, `name`) VALUES (7777, \'钱先生\'); INSERT INTO `customer` (`id`, `name`) VALUES (16666, \'孙先生\'); INSERT INTO `customer` (`id`, `name`) VALUES (17777, \'李先生\'); INSERT INTO `customer` (`id`, `name`) VALUES (26666, \'周先生\'); INSERT INTO `customer` (`id`, `name`) VALUES (27777, \'吴先生\'); --测试ER分片(在mycat连接中imall数据库中执行) INSERT INTO `order_info` (`order_id`, `uid`, `nums`, `state`, `create_time`, `update_time`) VALUES (1, 1000001, 1, 2, \'2025-9-23 14:35:37\', \'2025-9-23 14:35:37\'); INSERT INTO `order_info` (`order_id`, `uid`, `nums`, `state`, `create_time`, `update_time`) VALUES (2, 1000002, 1, 2, \'Mycat 读写分离 数据库分库分表 中间件 安装部署,及简单使用Linux 部署 Mycat 实现 MariaDB 分库分表
Linux 部署 Mycat 实现 MariaDB 分库分表