@Configuration
public class ShardingSphereConfig {
@Bean
public DataSource dataSource() {
// 配置真实数据源
Map<String, DataSource> dataSourceMap = new HashMap<>();
// 配置第一个数据源
BasicDataSource dataSource1 = new BasicDataSource();
dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
dataSource1.setUrl("jdbc:mysql://localhost:3306/ds0");
dataSource1.setUsername("root");
dataSource1.setPassword("");
dataSourceMap.put("ds0", dataSource1);
// 配置第二个数据源
BasicDataSource dataSource2 = new BasicDataSource();
dataSource2.setDriverClassName("com.mysql.jdbc.Driver");
dataSource2.setUrl("jdbc:mysql://localhost:3306/ds1");
dataSource2.setUsername("root");
dataSource2.setPassword("");
dataSourceMap.put("ds1", dataSource2);
// 配置Order表规则
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTables().add(getOrderTableRuleConfiguration());
// 配置分片键生成策略
Properties properties = new Properties();
shardingRuleConfig.setShardingAlgorithmNames(getShardingAlgorithmNames(properties));
// 配置默认数据源
shardingRuleConfig.setDefaultDataSourceName("ds0");
// 获取ShardingSphereDataSource
return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, new ShardingRuleConfiguration[]{shardingRuleConfig}, new Properties());
}
private TableRuleConfiguration getOrderTableRuleConfiguration() {
TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration();
tableRuleConfig.setLogicTable("t_order");
tableRuleConfig.setActualDataNodes("ds${0..1}.t_order${0..1}");
tableRuleConfig.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
tableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order${order_id % 2}"));
return tableRuleConfig;
}
private ShardingAlgorithmNames getShardingAlgorithmNames(Properties properties) {
ShardingAlgorithmNames shardingAlgorithmNames = new ShardingA
评论已关闭