mycat单库分表
mycat是國內著名的java后端開源中間件,工作有點類似于nginx,大致就是攔截原始sql,通過配置的分庫分表規則處理sql語句,使得業務層無需考慮數據庫和表的
拆分邏輯。
以下是sprinboot, mybatis,mysql,mycat實現的單庫分表,mycat版本:1.6.5-release,os:windows10,mysql大小寫不敏感!
數據腳本(page_0~9 分表為page_0? ...? page_9總共10張表):
CREATE TABLE `page_0~9` (`uid` int(11) NULL DEFAULT NULL,`id` int(11) NULL DEFAULT NULL,`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,`url` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;schema配置(單庫,10表)
<mycat:schema xmlns:mycat="http://io.mycat/"><schema name="auditbus" checkSQLschema="true" sqlMaxLimit="100"><!-- auto sharding by id (long) --><table name="page" subTables="page_$0-9" dataNode="dn1" rule="mod-long"></table></schema><dataNode name="dn1" dataHost="datahost1" database="auditbus" /><dataHost name="datahost1" maxCon="100" minCon="4" balance="0"writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100"><heartbeat>select user()</heartbeat><!-- can have multi write hosts --><writeHost host="hostM1" url="127.0.0.1:3306" user="root" password="tan1997"><!-- can have multi read hosts --><readHost host="hostS2" url="127.0.0.1:3306" user="root" password="tan1997"/></writeHost></dataHost> </mycat:schema>server.xml,配置訪問認證,端口等
<mycat:server xmlns:mycat="http://io.mycat/"><system><property name="defaultSqlParser">druidparser</property><property name="serverPort">8066</property></system><user name="root"><property name="password">pwd</property><property name="schemas">auditbus</property></user> </mycat:server>rule.xml,配置分表規則
<tableRule name="mod-long"><rule><columns>uid</columns><algorithm>mod-long</algorithm></rule> </tableRule><function name="mod-long" class="io.mycat.route.function.PartitionByMod"><!-- how many data nodes or subTables --><property name="count">10</property> </function>示例所用mycat+配置:https://download.csdn.net/download/qq_41633199/14929669
springboot配置(數據庫地址寫mycat的,其余不需要修改):
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedruid:url: jdbc:mysql://localhost:8066/auditbus?characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=truedriver-class-name: com.mysql.jdbc.Driverusername: rootpassword: pwdname: auditbushttp:encoding:charset: UTF-8mybatis:mapper-locations: classpath:/mybatis/mybatis-*.xml業務應用這邊需要注意mycat與mysql連接jar包的兼容性問題,筆者之前使用8.X.X的版本導致無法連接mycat,后來切換到如下版本才得以連上:
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.34</version><scope>runtime</scope> </dependency>mycat可能會出現表名大小寫問題導致schema找不到的bug,這點需要注意,筆者使用的mycat版本會將表名在代碼中轉成大寫,因此mysql要是表名大小寫敏感的話需要留意下。
總結
- 上一篇: Apexchart整数多出小数点
- 下一篇: js判断对象是否是json对象