阿飞Javaer,转载请注明原创出处,谢谢!
上篇文章sharding-jdbc源码之数据源介绍了通过Java硬编码创建ShardingDataSource。这篇文章通过分析sharding-jdbc-config-parent
模块,学习如何通过YAML配置或者spring配置创建ShardingDataSource;sharding-jdbc-config-parent
模块包含了三个子模块,关系如下图所示:
sharding-jdbc-config-parent
|__sharding-jdbc-config-common
|__sharding-jdbc-config-spring
|__sharding-jdbc-config-yaml
无论是yaml方式还是spring方式配置ShardingDataSource,最终都会转化为sharding-jdbc-config-common中定义的对象;接下来对两种方式进行源码分析:
YAML配置
可以通过
sharding-jdbc-example-config-yaml
模块中YamlWithAssignedDataSourceMain.java进行debug;通过YamlWithAssignedDataSourceMain.java源码可知,yaml方式配置数据库的核心源码在YamlShardingDataSource中;
public final class YamlWithAssignedDataSourceMain {
public static void main(final String[] args) throws Exception {
YamlShardingDataSource dataSource = new YamlShardingDataSource(
new File(YamlWithAssignedDataSourceMain.class.getResource("/META-INF/withAssignedDataSource.yaml").getFile()));
... ...
}
}
说明:withAssignedDataSource.yaml的内容请自行查看源码;
com.dangdang.ddframe.rdb.sharding.config.yaml.api.YamlShardingDataSource.java
位于sharding-jdbc-config-yaml
模块中,核心源码如下:
public class YamlShardingDataSource extends ShardingDataSource {
// 通过yaml文件配置数据源的方式
public YamlShardingDataSource(final File yamlFile) throws IOException, SQLException {
// unmarshal(yamlFile)方法是解析yaml文件的核心源码,其作用是将yaml文件解释为YamlConfig(父类是ShardingRuleConfig)
super(new ShardingRuleBuilder(yamlFile.getName(), unmarshal(yamlFile)).build(), unmarshal(yamlFile).getProps());
}
... ...
private static YamlConfig unmarshal(final File yamlFile) throws IOException {
try (
FileInputStream fileInputStream = new FileInputStream(yamlFile);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8")
) {
// yaml解释依赖第三方组件:org.yaml.snakeyaml; config-all.yaml内容解释成ShardingRuleConfig
return new Yaml(new Constructor(YamlConfig.class)).loadAs(inputStreamReader, YamlConfig.class);
}
}
private static YamlConfig unmarshal(final byte[] yamlByteArray) throws IOException {
return new Yaml(new Constructor(YamlConfig.class)).loadAs(new ByteArrayInputStream(yamlByteArray), YamlConfig.class);
}
}
通过这段源码可知,接下来就会调用ShardingDataSource的构造方法,因为YamlShardingDataSource构造方法中调用了super(),而且YamlShardingDataSource继承自ShardingDataSource;
spring配置
可以通过
sharding-jdbc-example-config-spring
模块中SpringNamespaceWithAssignedDataSourceMain.java进行debug;其源码就是加载applicationContextWithAssignedDataSource.xml
文件,该文件中<rdb>
节点即sharding-jdbc定义节点部分的内容如下:
<rdb:strategy id="databaseStrategy" sharding-columns="user_id" algorithm-expression="dbtbl_${user_id.longValue() % 2}"/>
<rdb:strategy id="orderTableStrategy" sharding-columns="order_id" algorithm-expression="t_order_${order_id.longValue() % 4}"/>
<rdb:strategy id="orderItemTableStrategy"</