原文链接
https://blog.csdn.net/u012394095/article/details/81301034
spring boot Yaml方式
@Bean(name = "testDataSource")
public DataSource testDataSource() throws IOException {
String yml = "jdbc/testDataSource.yaml";
Resource certResource = new ClassPathResource(yml);
DataSource dataSource = null;
try (InputStream is = certResource.getInputStream()) {
byte[] bytes = input2byte(is);
dataSource = new YmlByteArrayDataSource("testDataSource", bytes);
}
return dataSource;
}
定义一个Config类,配置数据源,上面的代码很简单,无非就是获取yaml文件,然后通过YmlByteArrayDataSource创建一个dataSource
public class YmlByteArrayDataSource extends ShardingDataSource {
public YmlByteArrayDataSource(String logroot, final byte[] ymlByteArray) throws IOException{
super(new ShardingRuleBuilder(logroot, unmarshal(ymlByteArray)).build(), unmarshal(ymlByteArray).getProps());
}
private static YamlConfig unmarshal(final byte[] ymlByteArray) throws IOException {
return new Yaml(new Constructor(YamlConfig.class)).loadAs(new ByteArrayInputStream(ymlByteArray), YamlConfig.class);
}
}
YmlByteArrayDataSource继承了ShardingDataSource,调用了super方法,创建一个dataSource,
YamlConfig继承了ShardingRuleConfig , 因此unmarshal方法就是读取yaml文件,然后构建一个ShardingRuleConfig 对象用来创建ShardingDataSource
yaml配置如下
dataSource:
ds_0: !!org.apache.commons.dbcp.BasicDataSource # 数据源连接池类型。
driverClassName: com.mysql.jdbc.Driver # 数据库驱动
url: jdbc:mysql://localhost:3306/ds_yaml_0 # 地址
username: root # 用户名
password: # 密码
ds_1: !!org.apache.commons.dbcp.BasicDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ds_yaml_1
username: root
password:
tables: # 分表规则
t_order: # 表的别称,用来写SQL,sharding-jdbc会用这个来查找真实的数据库表
actualTables: t_order_${0..1} # 真实的数据库表
tableStrategy: # 分表策略
shardingColumns: order_id # 分片ID
algorithmExpression: t_order_${order_id.longValue() % 2} # 分片策略
t_order_item: # 和t_order的一样的意义
actualTables: t_order_item_${0..1}
#绑定表中其余的表的策略与第一张表的策略相同
tableStrategy:
shardingColumns: order_id
algorithmExpression: t_order_item_${order_id.longValue() % 2}
bindingTables:
- tableNames: t_order,t_order_item
#默认数据库分片策略
defaultDatabaseStrategy:
shardingColumns: user_id # 使用user_id 来分库
algorithmExpression: ds_${user_id.longValue() % 2}
props:
sql.show: false # 是否显示SQL
上面的yaml配置一一对应ShardingRuleConfig里面的属性 .。
public class ShardingRuleConfig {
private Map dataSource = new HashMap();
private String defaultDataSourceName;
private Map tables = new HashMap();
private List bindingTables = new ArrayList();
private StrategyConfig defaultDatabaseStrategy;
private StrategyConfig defaultTableStrategy;
private String keyGeneratorClass;
}
spring boot 硬编码配置数据源
private static ShardingDataSource getShardingDataSource() throws SQLException {
// 构造DataSourceRule,即key与数据源的KV对;
DataSourceRule dataSourceRule = new DataSourceRule(createDataSourceMap());
// 建立逻辑表是t_order,实际表是t_order_0,t_order_1的TableRule
TableRule orderTableRule = TableRule.builder("t_order").
actualTables(Arrays.asList("t_order_0", "t_order_1")).dataSourceRule(dataSourceRule).build();
// 建立逻辑表是t_order_item,实际表是t_order_item_0,t_order_item_1的TableRule
TableRule orderItemTableRule = TableRule.builder("t_order_item").
actualTables(Arrays.asList("t_order_item_0", "t_order_item_1")).
dataSourceRule(dataSourceRule).build();
ShardingRule shardingRule = ShardingRule.builder()
.dataSourceRule(dataSourceRule)
.tableRules(Arrays.asList(orderTableRule, orderItemTableRule))
// 增加绑定表--绑定表代表一组表,这组表的逻辑表与实际表之
// 间的映射关系是相同的。比如t_order与t_order_item就是这样一组绑定表关系,它们的分库与 // 分表策略是完全相同的,那么可以使用它们的表规则将它们配置成绑定表,
// 绑定表所有路由计算将会只使用主表的策略;
.bindingTableRules(Collections.singletonList(new BindingTableRule(Arrays.asList(orderTableRule, orderItemTableRule))))
// 指定数据库sharding策略--根据user_id字段的值取模
.databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
// 指定表sharding策略--根据order_id字段的值取模
.tableShardingStrategy(new TableShardingStrategy("order_id", new ModuloTableShardingAlgorithm())).build();
return new ShardingDataSource(shardingRule);
}
// 创建两个数据源,一个是ds_jdbc_0,一个是ds_jdbc_1,并绑定映射关系key
private static Map createDataSourceMap() {
Map result = new HashMap<>(2);
result.put("ds_jdbc_0", createDataSource("ds_jdbc_0"));
result.put("ds_jdbc_1", createDataSource("ds_jdbc_1"));
return result;
}
// 以dbcp组件创建一个数据源
private static DataSource createDataSource(final String dataSourceName) {
BasicDataSource result = new BasicDataSource();
result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
result.setUrl(String.format("jdbc:mysql://localhost:3306/%s", dataSourceName));
result.setUsername("root");
// sharding-jdbc默认以密码为空的root用户访问,如果修改了root用户的密码,这里修改为真实的密码即可;
result.setPassword("");
return result;
}
spring xml 方式