场景: 雪花ID 都是偶数,根据ID 取模,肯定只会落到偶数的表里,所以要自定义分片算法
首先得去git 拉取一份mycat 服务代码
新建一个算法类 把ID最后一个字符去掉再取模(把普通的取模算法做一点修改即可)
package io.mycat.route.function;
import io.mycat.config.model.rule.RuleAlgorithm;
import java.math.BigInteger;
/**
* 自定义算法 字符串截取后取模,
* 字符串截取倒数第2位 取模 (雪花ID 最后一位永远都是偶数)
*/
public class SubStringPartitionByMod extends AbstractPartitionAlgorithm implements RuleAlgorithm {
private int count;
@Override
public void init() {
}
public void setCount(int count) {
this.count = count;
}
@Override
public Integer calculate(String columnValue) {
BigInteger bigNum = new BigInteger(columnValue.substring(0, columnValue.length() - 1)).abs();
return (bigNum.mod(BigInteger.valueOf(count))).intValue();
}
@Override
public int getPartitionNum() {
int nPartition = this.count;
return nPartition;
}
}
在 rule.xml 添加规则
<!-- 自定义算法 字符串截取后取模 -->
<tableRule name="subStr-mod-long">
<rule>
<columns>id</columns>
<algorithm>subStr-mod-long</algorithm>
</rule>
</tableRule>
<function name="subStr-mod-long" class="io.mycat.route.function.SubStringPartitionByMod">
<!-- how many data nodes -->
<property name="count">2</property>
</function>
配置schema.xml
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<schema name="TESTDB" checkSQLschema="false" sqlMaxLimit="100" randomDataNode="dn1">
<!-- auto sharding by id (long) -->
<!--splitTableNames 启用<table name 属性使用逗号分割配置多个表,即多个表使用这个配置-->
<!--fetchStoreNodeByJdbc 启用ER表使用JDBC方式获取DataNode-->
<!-- 需要分表的表 -->
<table name="accept_content" primaryKey="id" dataNode="dn1" subTables="accept_content_$0-1" rule="subStr-mod-long" >
</table>
<table name="accept_file_content_relation" primaryKey="id" dataNode="dn1" >
</table>
<table name="accept" primaryKey="id" dataNode="dn1" >
</table>
<table name="accept_file" primaryKey="id" dataNode="dn1" >
</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="supervisor_test" />
<!--<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="123456">
</writeHost>
<!-- <writeHost host="hostM2" url="localhost:3316" user="root" password="123456"/> -->
</dataHost>
</mycat:schema>
版权声明:本文为weixin_43850799原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。