先说说初始化过程:
org.apache.shardingsphere.core.yaml.swapper.impl.KeyGeneratorConfigurationYamlSwapper.swap
org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration开始初始化,执行构造方法,里面有三个参数:
public KeyGeneratorConfiguration(String type, String column, Properties properties) {
super(type, properties);
Preconditions.checkArgument(!Strings.isNullOrEmpty(column), "Column is required.");
this.column = column;
}
org.apache.shardingsphere.api.config.TypeBasedSPIConfiguration执行构造方法
org.apache.shardingsphere.core.rule.ShardingRule执行构造方法,这里面初始化很多内容:
public ShardingRule(ShardingRuleConfiguration shardingRuleConfig, Collection<String> dataSourceNames) { Preconditions.checkArgument(!dataSourceNames.isEmpty(), "Data sources cannot be empty."); this.shardingRuleConfig = shardingRuleConfig; this.shardingDataSourceNames = new ShardingDataSourceNames(shardingRuleConfig, dataSourceNames); this.tableRules = this.createTableRules(shardingRuleConfig); this.bindingTableRules = this.createBindingTableRules(shardingRuleConfig.getBindingTableGroups()); this.broadcastTables = shardingRuleConfig.getBroadcastTables(); this.defaultDatabaseShardingStrategy = this.createDefaultShardingStrategy(shardingRuleConfig.getDefaultDatabaseShardingStrategyConfig()); this.defaultTableShardingStrategy = this.createDefaultShardingStrategy(shardingRuleConfig.getDefaultTableShardingStrategyConfig()); this.defaultShardingKeyGenerator = this.createDefaultKeyGenerator(shardingRuleConfig.getDefaultKeyGeneratorConfig()); this.masterSlaveRules = this.createMasterSlaveRules(shardingRuleConfig.getMasterSlaveRuleConfigs()); this.shardingEncryptorEngine = this.createShardingEncryptorEngine(shardingRuleConfig.getEncryptRuleConfig()); }
下面讲一下具体的配置方法:
首先按照spi规范,在如下位置创建文件,名称为:org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator
文件里的内容:com.hy.sharding.spi.MySnowflakeShardingKeyGenerator
就是你的自定义类。
配置文件中这样写,看最后就可以了。keyGenerator的部分。
tables:
user: #user表
key-generator-column-name: id #主键
actualDataNodes: ds0.user$->{[0,1,2]} #数据节点,均匀分布
tableStrategy: #分表策略
inline: #行表达式
shardingColumn: id
algorithmExpression: user$->{id % 3} #按模运算分配
ugroup:
actualDataNodes: ds0.ugroup$->{[0,1,2]}
tableStrategy:
inline:
shardingColumn: uid
algorithmExpression: ugroup$->{uid % 3}
keyGenerator:
type: MYSNOWFLAKE
column: id
props:
workid: 1
对了,我的版本是
4.0.0-RC1