shardingjdbc使用详解

1.在已有的项目中添加jar包依赖


                org.apache.shardingsphere
                sharding-jdbc-spring-boot-starter
                4.0.0-RC1
            

2.Java方法添加分片配置


    @Bean(name = "myDataSource")
    public DataSource getShardingDataSource(@Qualifier("dataSourceOld") DataSource dataSource01) throws SQLException {
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
        shardingRuleConfig.getBindingTableGroups().add("bqhealth_cloud_main_index");
        shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("type", new MainIndexPreciseShardingAlgorithm()));
        Properties properties = new Properties();
        properties.setProperty("sql.show", sqlShow);
        return ShardingDataSourceFactory.createDataSource(createDataSourceMap(dataSource01), shardingRuleConfig, properties);
    }

    TableRuleConfiguration getOrderTableRuleConfiguration() {
        TableRuleConfiguration result = new TableRuleConfiguration("main_index", "db.main_index_${0..2}");
        return result;
    }

    Map createDataSourceMap(DataSource dataSource) {
        Map result = new HashMap<>();
        result.put("db", dataSource);
        return result;
    }

3.添加分片策略类

@Slf4j
public class MainIndexPreciseShardingAlgorithm implements PreciseShardingAlgorithm {

    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {

        for (String tableName : availableTargetNames) {
            if (tableName.endsWith(shardingValue.getValue() + "")) {
            	// 添加分片规则
                //log.info("doSharding >> shardingValue = {}, tableName = {}", shardingValue, tableName);
                return tableName;
            }
        }
        throw new IllegalArgumentException();
    }

}

你可能感兴趣的:(springboot,sharding-jdbc)