接上 MySQL集群部署,读写分离
但是代码调用非常麻烦,写一大堆代码。所以就直接没写。。。。
MyCat前身为阿里Cobar,Cobar被阿里放弃后,被开源爱好者改造成了MyCat。
开源数据库中间件,实现了MySQL协议的数据库中间件服务器。
默认端口8066.
主要用来做
1)数据库读写分离:应用连接MyCat自动实现读写分离;
2)分库分表:水平(横向)切分、垂直(纵向)切分。
水平拆分:为了解决大表问题(如1000万条Orders数据),根据表中某列数据拆分,拆分到不同数据库中Orders表以解决大表带来问题。
如1000万条Order,分为5个库,每个库的Order存200万条。根据id%5=0-4存储到不同的位置中。
基于上面的拆分规则,Order业务至少有5*2主库*2从库=20个数据源。可以用MyCat配置规则算法实现。
垂直拆分:一个数据库有100张表,访问人数增加会形成IO竞争。如1000W人访问订单表,1人访问用户表,因数据库连接上限导致1人用户登录变慢,且所有数据全部存放在一个库中,造成磁盘压力。
为解决表特别多问题,使用垂直拆分,根据不同表的业务关系将表存放到不同库。不同表放在不同库,解决IO竞争问题。
如用户模块、订单模块、商品模块等5个模块,不同业务放在不同的库。
基于上面拆分规则,会有 5个模块*4个水平拆分*2主库*2从库= 80个数据源。同样可以桥接MyCat来根据规则实现。
垂直拆分后一般分组按模块独立开发,基本不会跨模块访问。当需要跨模块时,使用对方模块提供的接口。
拆分优先级:缓存降低数据库读操作 -> 读写分离降低数据库写操作 -> 垂直拆分 -> 水平拆分(分库)
-> 水平拆分(分表)。
1,环境搭建
下载 https://github.com/MyCATApache/Mycat-Server/releases
现在最后一个稳定版是1.6.7.5 两年没更新了。。。。
解压
[senrsl@localhost mycat]$ tar zxvf
Mycat-server-1.6.7.5-release-20200422133810-linux.tar.gz
[senrsl@localhost mycat]$ ll
总用量 22668
drwxrwxr-x. 6 senrsl senrsl 73 7月 2 06:34 mycat
-rw-r--r--. 1 senrsl senrsl 23209170 7月 2 06:33
Mycat-server-1.6.7.5-release-20200422133810-linux.tar.gz
[senrsl@localhost mycat]$
[senrsl@localhost mycat]$ ll mycat/
总用量 12
drwxrwxr-x. 2 senrsl senrsl 190 7月 2 06:34 bin
drwxrwxr-x. 2 senrsl senrsl 6 4月 15 2020 catlet
drwxrwxr-x. 4 senrsl senrsl 4096 7月 2 06:34 conf
drwxrwxr-x. 2 senrsl senrsl 4096 7月 2 06:34 lib
-rwxrwxr-x. 1 senrsl senrsl 227 4月 22 2020 version.txt
[senrsl@localhost mycat]$
2,配置文件server.xml
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="ignoreUnknownCommand">0</property><!-- 0遇上没有实现的报文(Unknown command:),就会报错、1为忽略该报文,返回ok报文。
在某些mysql客户端存在客户端已经登录的时候还会继续发送登录报文,mycat会报错,该设置可以绕过这个错误-->
<property name="useHandshakeV10">1</property>
<property name="removeGraveAccent">1</property>
<property name="useSqlStat">0</property> <!-- 1为开启实时统计、0为关闭 -->
<property name="useGlobleTableCheck">0</property> <!-- 1为开启全加班一致性检测、0为关闭 -->
<property name="sqlExecuteTimeout">300</property> <!-- SQL 执行超时 单位:秒-->
<property name="sequenceHandlerType">1</property>
<!--<property name="sequnceHandlerPattern">(?:(\s*next\s+value\s+for\s*MYCATSEQ_(\w+))(,|\)|\s)*)+</property>
INSERT INTO `travelrecord` (`id`,user_id) VALUES ('next value for MYCATSEQ_GLOBAL',"xxx");
-->
<!--必须带有MYCATSEQ_或者 mycatseq_进入序列匹配流程 注意MYCATSEQ_有空格的情况-->
<property name="sequnceHandlerPattern">(?:(\s*next\s+value\s+for\s*MYCATSEQ_(\w+))(,|\)|\s)*)+</property>
<property name="subqueryRelationshipCheck">false</property> <!-- 子查询中存在关联查询的情况下,检查关联字段中是否有分片字段 .默认 false -->
<property name="sequenceHanlderClass">io.mycat.route.sequence.handler.HttpIncrSequenceHandler</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 | type 2 NettyBufferPool -->
<property name="processorBufferPoolType">0</property>
<!--默认是65535 64K 用于sql解析时最大文本长度 -->
<!--<property name="maxStringLiteralLength">65535</property>-->
<!--<property name="sequenceHandlerType">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="dataNodeIdleCheckPeriod">300000</property> 5 * 60 * 1000L; //连接空闲检查
<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">0</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="XARecoveryLogBaseDir">./</property>-->
<!-- XA Recovery Log日志名称 -->
<!--<property name="XARecoveryLogBaseName">tmlog</property>-->
<!--如果为 true的话 严格遵守隔离级别,不会在仅仅只有select语句的时候在事务中切换连接-->
<property name="strictTxIsolation">false</property>
<!--如果为0的话,涉及多个DataNode的catlet任务不会跨线程执行-->
<property name="parallExecute">0</property>
</system>
<!-- 全局SQL防火墙设置 -->
<!--白名单可以使用通配符%或着*-->
<!--例如<host host="127.0.0.*" user="root"/>-->
<!--例如<host host="127.0.*" user="root"/>-->
<!--例如<host host="127.*" user="root"/>-->
<!--例如<host host="1*7.*" user="root"/>-->
<!--这些配置情况下对于127.0.0.1都能以root账户登录-->
<!--
<firewall>
<whitehost>
<host host="1*7.0.0.*" user="root"/>
</whitehost>
<blacklist check="false">
</blacklist>
</firewall>
-->
<user name="root" defaultAccount="true"> //这里root改成mycat方便与mysql区分
<property name="password">123456</property>
<property name="schemas">TESTDB</property> //两个TESTDB改成MYCATDB,方便区分
<property name="defaultSchema">TESTDB</property>
<!--No MyCAT Database selected 错误前会尝试使用该schema作为schema,不设置则为null,报错 -->
<!-- 表级 DML 权限设置 -->
<!--
<privileges check="false">
<schema name="TESTDB" dml="0110" >
<table name="tb01" dml="0000"></table>
<table name="tb02" dml="1111"></table>
</schema>
</privileges>
-->
</user>
<user name="user">
<property name="password">user</property>
<property name="schemas">TESTDB</property>//MYCATDB
<property name="readOnly">true</property>
<property name="defaultSchema">TESTDB</property>
</user>
</mycat:server>
3,配置文件scheme.xml
[senrsl@localhost mycat]$ cat conf/schema.xml
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<schema name="TESTDB" checkSQLschema="true" sqlMaxLimit="100" randomDataNode="dn1"> //逻辑库TESTDB
<!-- auto sharding by id (long) -->
<!--splitTableNames 启用<table name 属性使用逗号分割配置多个表,即多个表使用这个配置-->
<!--fetchStoreNodeByJdbc 启用ER表使用JDBC方式获取DataNode-->
<table name="customer" primaryKey="id" dataNode="dn1,dn2" rule="sharding-by-intfile" autoIncrement="true" fetchStoreNodeByJdbc="true">
<childTable name="customer_addr" primaryKey="id" joinKey="customer_id" parentKey="id"> </childTable>
</table>
<!-- <table name="oc_call" primaryKey="ID" dataNode="dn1$0-743" rule="latest-month-calldate"
/> -->
</schema>
<!-- <dataNode name="dn1$0-743" dataHost="localhost1" database="db$0-743"
/> -->
<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="sequoiadb1" database="SAMPLE" />
<dataNode name="jdbc_dn1" dataHost="jdbchost" database="db1" />
<dataNode name="jdbc_dn2" dataHost="jdbchost" database="db2" />
<dataNode name="jdbc_dn3" dataHost="jdbchost" database="db3" /> -->
<dataHost name="localhost1" maxCon="1000" minCon="10" balance="0"
writeType="0" dbType="mysql" dbDriver="jdbc" switchType="1" slaveThreshold="100">
<heartbeat>select user()</heartbeat>
<!-- can have multi write hosts -->
<writeHost host="hostM1" url="jdbc:mysql://localhost:3306" user="root"
password="root">
</writeHost>
<!-- <writeHost host="hostM2" url="localhost:3316" user="root" password="123456"/> -->
</dataHost>
<!--
<dataHost name="sequoiadb1" maxCon="1000" minCon="1" balance="0" dbType="sequoiadb" dbDriver="jdbc">
<heartbeat> </heartbeat>
<writeHost host="hostM1" url="sequoiadb://1426587161.dbaas.sequoialab.net:11920/SAMPLE" user="jifeng" password="jifeng"></writeHost>
</dataHost>
<dataHost name="oracle1" maxCon="1000" minCon="1" balance="0" writeType="0" dbType="oracle" dbDriver="jdbc"> <heartbeat>select 1 from dual</heartbeat>
<connectionInitSql>alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss'</connectionInitSql>
<writeHost host="hostM1" url="jdbc:oracle:thin:@127.0.0.1:1521:nange" user="base" password="123456" > </writeHost> </dataHost>
<dataHost name="jdbchost" maxCon="1000" minCon="1" balance="0" writeType="0" dbType="mongodb" dbDriver="jdbc">
<heartbeat>select user()</heartbeat>
<writeHost host="hostM" url="mongodb://192.168.0.99/test" user="admin" password="123456" ></writeHost> </dataHost>
<dataHost name="sparksql" maxCon="1000" minCon="1" balance="0" dbType="spark" dbDriver="jdbc">
<heartbeat> </heartbeat>
<writeHost host="hostM1" url="jdbc:hive2://feng01:10000" user="jifeng" password="jifeng"></writeHost> </dataHost> -->
<!-- <dataHost name="jdbchost" maxCon="1000" minCon="10" balance="0" dbType="mysql"
dbDriver="jdbc"> <heartbeat>select user()</heartbeat> <writeHost host="hostM1"
url="jdbc:mysql://localhost:3306" user="root" password="123456"> </writeHost>
</dataHost> -->
</mycat:schema>[senrsl@localhost mycat]$
4,读写分离配置
server.xml 改下面两处
<user name="mycat" defaultAccount="true">
<property name="password">123456</property>
<property name="schemas">MYCATDB</property>
<property
name="defaultSchema">MYCATDB</property>
<!--No MyCAT Database selected
错误前会尝试使用该schema作为schema,不设置则为null,报错 -->
<!-- 表级 DML 权限设置 -->
<!--
<privileges check="false">
<schema name="TESTDB" dml="0110" >
<table name="tb01" dml="0000"></table>
<table name="tb02" dml="1111"></table>
</schema>
</privileges>
-->
</user>
<user name="user">
<property name="password">user</property>
<property name="schemas">MYCATDB</property>
<property name="readOnly">true</property>
<property
name="defaultSchema">MYCATDB</property>
</user>
scheme.xml内容如下
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<schema name="MYCATDB" checkSQLschema="true" sqlMaxLimit="100" dataNode="dn1">
</schema>
<dataNode name="dn1" dataHost="localhost1" database="test202201" />
<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.0.122:3306" user="root"
password="0123456">
<readHost host="hostS1" url="192.168.0.125:3306" user="root" password="0123456" />
</writeHost>
<writeHost host="hostM2" url=" 192.168.0.142:3306" user="root"
password="0123456">
<readHost host="hostS2" url="192.168.0.111:3306" user="root" password="0123456" />
</writeHost>
</dataHost>
</mycat:schema>
5,启动
启动后查看进程是否存在,否则就去看 log报错。。。。
[senrsl@localhost mycat]$ bin/mycat start
Starting Mycat-server...
[senrsl@localhost mycat]$ ps -ef | grep mycat
报错1:
[senrsl@localhost mycat]$ cat wrapper.log
FATAL | wrapper | 2022/07/02 07:15:48 | ERROR: Could not write
pid file /home/senrsl/mycat/mycat/logs/mycat.pid: No such file or
directory
手动创建logs/mycat.pid
6,设置mysql允许远程连接
mysql> grant all on *.* to 'root'@'%' identified by '0123456'
with grant option;
Query OK, 0 rows affected, 1 warning (0.00 sec)
昨天能连,今天莫名其妙就连不上了。执行上面sql就好了。。。。
莫名其妙,之前全都不行,四台机器之设置了一台结果其他三台也行了。。。。
7,读写分离测试
连接mycat,使用连接mysql方式,端口8066,mycat/123456
可以看到里面有MYCATDB这个库。里面有user表。
执行插入数据等测试,确认 mysql主从库同步。
INSERT INTO users(name) VALUES("sql插入测试");
自动实现读写分离。
此时双主双从模式、122、142互为主从、125为122的从,111为142的从。
此时如果122宕机,125从也不会参与读了。只有142参与写,111参与读。
恢复122后,122和125会自动同步数据到最新。
8,SpringBoot调用测试
1)新建TestMyCat SpringBoot项目
2)依赖
<!-- 连接 Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <!-- 连接MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>5.1.46</version> </dependency>
3)数据库连接配置,直接配到MyCat上
# 使用MyCat连接 # 数据库驱动: spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 数据源名称 #spring.datasource.name=defaultDataSource # 数据库连接地址 spring.datasource.url=jdbc:mysql://192.168.0.122:8066/MYCATDB # 数据库用户名&密码: spring.datasource.username=mycat spring.datasource.password=123456
4)添加映射自动生成配置
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <!--配置文件的位置--> <configurationFile>GeneratorMapper.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
5)添加映射文件
项目根目录GeneratorMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定连接数据库的JDBC驱动包所在位置,指定到你本机的完整路径 -->
<classPathEntry location="/Users/senrsl/.m2/repository/mysql/mysql-connector-java/5.1.46/mysql-connector-java-5.1.46.jar"/>
<!-- 配置table表信息内容体,targetRuntime指定采用MyBatis3的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.0.122:8066/MYCATDB"
userId="mycat"
password="123456">
</jdbcConnection>
<!-- 生成model类,targetPackage指定model类的包名, targetProject指定生成的model放在eclipse的哪个工程下面-->
<javaModelGenerator targetPackage="dc.test.model" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在eclipse的哪个工程下面 -->
<sqlMapGenerator targetPackage="dc.test.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在eclipse的哪个工程下面 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="dc.test.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 数据库表名及对应的Java模型类名 -->
<table tableName="users"
domainObjectName="Users"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
6)映射生成
Maven -> mybatis-generator
配图1
生成文件如下,给Mapper添加注解
配图2
7)编写service
@Service public class UserService { @Resource private UsersMapper usersMapper; public void insert(Users user){ usersMapper.insert(user); } public void selectAll(){ List<Users> list = usersMapper.selectAll(); for (Users user:list) { System.out.println(user.toString()); } } }
8)运行
@SpringBootApplication public class TestApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(TestApplication.class, args); String[] arr = context.getBeanNamesForAnnotation(org.springframework.stereotype.Service.class); System.out.println("迭代" + arr); for (String str : arr) { System.out.println("is " + str); } UserService userService = context.getBean("userService",UserService.class); userService.insert(new Users("张三" + new Date())); userService.selectAll(); } }
报错1:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'UserService' available
把启动类Application放在跟Service平级的目录会取不到,必须要放在外面才能取到。。。。
此处配图3
9,水平拆分测试
1)环境准备
在vm121创建三个库,test202202、03、04
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| test2022 |
| test202201 |
| test202202 |
| test202203 |
| test202204 |
+--------------------+
9 rows in set (0.00 sec)
mysql>
每个库创建表t_orders
/*
Navicat Premium Data Transfer
Source Server : vm121
Source Server Type : MySQL
Source Server Version : 50737
Source Host : 192.168.0.122:3306
Source Schema : test202202
Target Server Type : MySQL
Target Server Version : 50737
File Encoding : 65001
Date: 04/07/2022 14:45:57
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_orders
-- ----------------------------
DROP TABLE IF EXISTS `t_orders`;
CREATE TABLE `t_orders` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`createTime` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET FOREIGN_KEY_CHECKS = 1;
其他三个从机也就都同步了这三个库了。。。。
修改:id设置为不自增,把自增给MyCat来实现。。。。
2)修改MyCat配置文件
server.xml同读写分离
scheme.xml
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<schema name="MYCATDB" checkSQLschema="true" sqlMaxLimit="100" randomDataNode="dn1">
<table name="t_orders" primaryKey="id" dataNode="dn1,dn2,dn3" rule="mod-long" autoIncrement="true" >
</table>
</schema>
<dataNode name="dn1" dataHost="localhost1" database="test202202" />
<dataNode name="dn2" dataHost="localhost1" database="test202203" />
<dataNode name="dn3" dataHost="localhost1" database="test202204" />
<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.0.122:3306" user="root"
password="0123456">
<readHost host="hostS1" url="192.168.0.125:3306" user="root" password="0123456" />
</writeHost>
<writeHost host="hostM2" url=" 192.168.0.142:3306" user="root"
password="0123456">
<readHost host="hostS2" url="192.168.0.112:3306" user="root" password="0123456" />
</writeHost>
</dataHost>
</mycat:schema>
其中table标签下rule配置于conf/rule.xml
3)替换配置重启服务
[root@localhost mycat]# ./bin/mycat stop
Stopping Mycat-server...
Stopped Mycat-server.
[root@localhost mycat]# ./bin/mycat start
Starting Mycat-server...
[root@localhost mycat]#
4)测试
navicat连接mycat库
插入测试
INSERT into t_orders(name)VALUES('张三');
报错1:
INSERT into t_orders(name)VALUES('张三')
> 1003 - mycat sequnce
err.io.mycat.config.util.ConfigException: can't find definition
for sequence :T_ORDERS
> Time: 0s
1064 - can't find table define in schema TRIGGERS schema:MYCATDB
能读不能写
修改
[root@localhost mycat]# cat conf/sequence_db_conf.properties
#sequence stored in datanode
GLOBAL=dn1
COMPANY=dn1
CUSTOMER=dn1
ORDERS=dn1
T_ORDERS=dn1 //添加需要自增长的表名称
[root@localhost mycat]#
报错2:
INSERT INTO t_orders(name)VALUES("张三")
> 1003 - mycat sequnce err.java.lang.RuntimeException: can't
fetch sequnce in db,sequnce :T_ORDERS detail:FUNCTION
test202202.mycat_seq_nextval does not exist
> Time: 0s
解决,三个数据库依次执行
#添加表
DROP TABLE IF EXISTS MYCAT_SEQUENCE;
CREATE TABLE MYCAT_SEQUENCE (
NAME VARCHAR (50) NOT NULL,
current_value INT NOT NULL,
increment INT NOT NULL DEFAULT 100,
PRIMARY KEY (NAME)
) ENGINE = INNODB ;
INSERT INTO MYCAT_SEQUENCE(name,current_value,increment) VALUES
('GLOBAL', 100000, 100);
DROP FUNCTION IF EXISTS `mycat_seq_currval`;
DELIMITER ;;
CREATE FUNCTION `mycat_seq_currval`(seq_name VARCHAR(50))
RETURNS varchar(64) CHARSET utf8
DETERMINISTIC
BEGIN DECLARE retval VARCHAR(64);
SET retval="-999999999,null";
SELECT concat(CAST(current_value AS
CHAR),",",CAST(increment AS CHAR) ) INTO retval
FROM MYCAT_SEQUENCE WHERE name = seq_name;
RETURN retval ;
END
;;
DELIMITER ;
DROP FUNCTION IF EXISTS `mycat_seq_nextval`;
DELIMITER ;;
CREATE FUNCTION `mycat_seq_nextval`(seq_name VARCHAR(50)) RETURNS
varchar(64)
CHARSET utf8
DETERMINISTIC
BEGIN UPDATE MYCAT_SEQUENCE
SET current_value = current_value + increment
WHERE name = seq_name;
RETURN mycat_seq_currval(seq_name);
END
;;
DELIMITER ;
DROP FUNCTION IF EXISTS `mycat_seq_setval`;
DELIMITER ;;
CREATE FUNCTION `mycat_seq_setval`(seq_name VARCHAR(50), value
INTEGER)
RETURNS varchar(64) CHARSET utf8
DETERMINISTIC
BEGIN UPDATE MYCAT_SEQUENCE
SET current_value = value
WHERE name = seq_name;
RETURN mycat_seq_currval(seq_name);
END
;;
DELIMITER ;
报错3:
INSERT INTO t_orders(name)VALUES("张三")
> 1003 - mycat sequnce err.java.lang.NumberFormatException: For
input string: "null"
> Time: 0s
mycat获取自增字段有三种方式:从配置文件0、从数据库1、本地时间戳2
对应配置在 server.xml
<property name="sequenceHandlerType">1</property>
默认是1,改成2使用本地时间戳方式。。。。
终于插入成功了。。。。
敢情前面那些都不用改。。。。
插入后,会自动分到不同的数据库中来存储。。。。
5)SpringBoot测试
生成mapper
<!-- 数据库表名及对应的Java模型类名 --> <!--<table tableName="users" domainObjectName="Users" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>--> <table tableName="t_orders" domainObjectName="Orders" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
OrdersMapper增加 @Mapper
编写Service
@Service public class OrderService { @Resource private OrdersMapper mapper; public void add(Orders orders) { mapper.insert(orders); } public void selectAll() { List<Orders> list = mapper.selectAll(); for (Orders order : list) { System.out.println(order.toString()); } } }
运行
@SpringBootApplication public class TestOrderApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(TestOrderApplication.class,args); OrderService orderService = (OrderService) context.getBean("orderService"); orderService.add(new Orders("李四",new Date())); orderService.selectAll(); } }
报错:
Error attempting to get column 'name' from result set. Cause:
java.sql.SQLException: Cannot convert value 'æµè¯' from column 2
to TIMESTAMP.
无语。。。。为啥不能映射timestamp....
10,垂直拆分测试
1)环境搭建
一个表拆三个库
还是用test202202、03、04
分别建 t_order2、t_good、t_users
都有两列 id、name
配图4
2)配置
server.xml同水平拆分
scheme.xml
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<schema name="MYCATDB" checkSQLschema="true" sqlMaxLimit="100" randomDataNode="dn1">
<table name="t_order2" primaryKey="id" dataNode="dn1" autoIncrement="true" >
</table>
<table name="t_goods" primaryKey="id" dataNode="dn2" autoIncrement="true" >
</table>
<table name="t_users" primaryKey="id" dataNode="dn3" autoIncrement="true" >
</table>
</schema>
<!-- <dataNode name="dn1$0-743" dataHost="localhost1" database="db$0-743"
/> -->
<dataNode name="dn1" dataHost="localhost1" database="test202202" />
<dataNode name="dn2" dataHost="localhost1" database="test202203" />
<dataNode name="dn3" dataHost="localhost1" database="test202204" />
<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.0.122:3306" user="root"
password="0123456">
<readHost host="hostS1" url="192.168.0.125:3306" user="root" password="0123456" />
</writeHost>
<writeHost host="hostM2" url=" 192.168.0.142:3306" user="root"
password="0123456">
<readHost host="hostS2" url="192.168.0.112:3306" user="root" password="0123456" />
</writeHost>
</dataHost>
</mycat:schema>
3)代码测试
操作多张数据表即可。
11,主键策略
server.xml中sequenceHandlerType值
本地0,数据库1,时间戳2
1)本地
修改值为0后,直接运行报错 mycat sequnce err.java.lang.NumberFormatException: null
修改
主键存储在
[root@localhost mycat]# cat conf/sequence_conf.properties
。。。
GLOBAL.CURID=10000
。。。。
报错:
Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
INSERT INTO t_order2(id,name)VALUES(next value for
MYCATSEQ_GLOBAL,"李四")
> 2013 - Lost connection to server during query
> Time: 0s
直接操作mysql插入可以,通过mycat插入就不行
但是通过mysql查询可以。。。。
能读不能写,查看写入配置是不是有问题,发现IP多了空格。。。。但改完后依然同样问题。
2)数据库方式
配置文件对应的是
[root@localhost mycat]# cat conf/sequence_db_conf.properties
#sequence stored in datanode
GLOBAL=dn1
COMPANY=dn1
CUSTOMER=dn1
ORDERS=dn1
[root@localhost mycat]#
3)时间戳方式
之前测试的方式。
特么的,不测了,MyCat基本每做一步都出一个bug。。。。
senRsl
2022年07月02日21:06:11
没有评论 :
发表评论