shardingjdbc使用の詳細
2312 ワード
1.既存のプロジェクトにjarパッケージ依存性を追加
2.Javaメソッドスライス構成の追加
3.スライスポリシークラスの追加
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();
}
}