@Configuration
public class ShardingJdbcConfig {
@Bean
public DataSource dataSource() {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
// 配置第一个数据源
Properties dataSourceProps = new Properties();
dataSourceProps.put("driverClassName", "com.mysql.jdbc.Driver");
dataSourceProps.put("url", "jdbc:mysql://localhost:3306/ds0");
dataSourceProps.put("username", "root");
dataSourceProps.put("password", "password");
DataSource dataSource0 = DataSourceFactory.createDataSource(dataSourceProps);
// 配置第二个数据源
Properties dataSourceProps1 = new Properties();
dataSourceProps1.put("driverClassName", "com.mysql.jdbc.Driver");
dataSourceProps1.put("url", "jdbc:mysql://localhost:3306/ds1");
dataSourceProps1.put("username", "root");
dataSourceProps1.put("password", "password");
DataSource dataSource1 = DataSourceFactory.createDataSource(dataSourceProps1);
// 配置读写分离
Map<String, DataSource> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds0", dataSource0);
dataSourceMap.put("ds1", dataSource1);
MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("ds0", dataSourceMap);
// 配置分表
shardingRuleConfig.getBindingTableGroups().add("t_order");
shardingRuleConfig.getBroadcastTables().add("t_config");
shardingRuleConfig.getTables().put("t_order", new TableRuleConfiguration("t_order", "ds${0..1}.t_order${0..1}"));
// 配置分片键和分片算法
shardingRuleConfig.getTables().get("t_order").setKeyGeneratorColumnName("order_id");
shardingRuleConfig.getTables().get("t_order").setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "ds${user_id % 2}"));
shardingRuleConfig.getTables().get("t_order").setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order${order_id % 2}"));
// 自定义复合分片键
ComplexKeysShardingStrategyConfiguration complexKeysShardingStrategyConfig = new ComplexKeysShardingStrategyConfiguration("t_order");
complexKeysShardingStrategyConfig.getShardingColumns().add("user_id");
complexKeysShardingStrategyConfig.getShardingColumns().add("order_id");
complexKeysShardingStrategyConfig.setKeyG
评论已关闭