All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yuweix.kuafu.sharding.strategy.DefaultStrategy Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package com.yuweix.kuafu.sharding.strategy;


import com.yuweix.kuafu.sharding.context.DatabaseSetting;
import com.yuweix.kuafu.sharding.context.ShardingContext;
import com.yuweix.kuafu.sharding.context.TableSetting;


/**
 * @author yuwei
 */
public class DefaultStrategy implements Strategy {
    @Override
    public String getPhysicalDatabaseName(String dbName, String tableName, T shardingVal) {
        DatabaseSetting dsetting = ShardingContext.getShardDatabaseSetting(dbName);
        if (dsetting == null) {
            throw new RuntimeException("[" + dbName + "]'s sharding-conf is required.");
        }
        TableSetting tsetting = ShardingContext.getShardSetting(tableName);
        if (tsetting == null) {
            throw new RuntimeException("[" + tableName + "]'s sharding-conf is required.");
        }
        return dbName + dsetting.getSplit() + String.format("%0" + dsetting.getSuffixLength() + "d", hash(shardingVal) % tsetting.getDatabaseSize());
    }

    @Override
    public String getPhysicalTableName(String tableName, T shardingVal) {
        TableSetting setting = ShardingContext.getShardSetting(tableName);
        if (setting == null) {
            throw new RuntimeException("[" + tableName + "]'s sharding-conf is required.");
        }
        return tableName + setting.getSplit() + String.format("%0" + setting.getSuffixLength() + "d", (hash(shardingVal) / setting.getDatabaseSize()) % setting.getTableSize());
    }

    private int hash(Object str) {
        if (str == null) {
            return 0;
        }
        return Math.abs(str.hashCode());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy