MyCat2 修改源码实现不使用http的自定义分库分表算法

84 阅读1分钟

使用场景

公司有4张表,目前每张表都大概有8000w左右数据,日常查询会很慢,需要分库,但是不能通过mycat提供的算法进行分库,我们这边维护了一个区域码,每个区域的数据放到一个库。

实施方案

1.使用mycat2 官方提供的自定义算法实现(http方式,每次插入数据都会访问接口)

/*+ mycat:createTable{
	"schemaName":"testSchema",
	"shardingTable":{
		"createTableSQL":"建表语句",
		"function":{
			"clazz":"io.mycat.router.custom.HttpCustomRuleFunction",
			"properties":{
				"name":"test",//分片算法名字,用于识别ER关系,名字相同意味着有相同的数据分布
				"shardingDbKeys":"",//分库键
				"shardingTableKeys":"id",//分表键
				"shardingTargetKeys":"",//分实例键
				"allScanPartitionTimeout":5,//全表扫描结果缓存时间,单位:"fetchTimeout":60000,//调用http服务超时时间,单位:毫秒
				"routerServiceAddress":"http://127.0.0.1:9066/router_service_address"//请求的接口地址
			}
		},
		"partition":{
			
		}
	},
	"tableName":"sharding"
} */;

当前用法需要提供一个 http://127.0.0.1:9066/router_service_address 类似的接口地址

请求参数

schemaName schema名称
tableName  表名
condition  条件

返回如下参数

[{"targetName":"prototype","dbIndex":0,"tableIndex":1,"index":1,"table":"sharding","schema":"testschema"}]

条件为空时,需要返回所有分库分表信息

缺点:每次插入数据都需要访问http,在数据迁移和大数据量插入时会非常慢

2.修改源码来快速响应

image.png 在源码中找到这个类

image.png 修改这个类使最后返回和http方式一样的参数,为极大增加响应速度

注意事项

首次配置好后启动mycat2 ,条件一定为空,要返回所有分库分表信息,mycat2会自动创建库,创建表