1.sharding-jdbc系列之 数据源配置
Posted sharedCode
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1.sharding-jdbc系列之 数据源配置相关的知识,希望对你有一定的参考价值。
精品源码
spring boot Yaml方式
1@Bean(name = "testDataSource")
2public DataSource testDataSource() throws IOException {
3 String yml = "jdbc/testDataSource.yaml";
4 Resource certResource = new ClassPathResource(yml);
5 DataSource dataSource = null;
6 try (InputStream is = certResource.getInputStream()) {
7 byte[] bytes = input2byte(is);
8 dataSource = new YmlByteArrayDataSource("testDataSource", bytes);
9 }
10 return dataSource;
11}
定义一个Config类,配置数据源,上面的代码很简单,无非就是获取yaml文件,然后通过YmlByteArrayDataSource创建一个dataSource
1public class YmlByteArrayDataSource extends ShardingDataSource {
2
3 public YmlByteArrayDataSource(String logroot, final byte[] ymlByteArray) throws IOException{
4 super(new ShardingRuleBuilder(logroot, unmarshal(ymlByteArray)).build(), unmarshal(ymlByteArray).getProps());
5 }
6
7 private static YamlConfig unmarshal(final byte[] ymlByteArray) throws IOException {
8 return new Yaml(new Constructor(YamlConfig.class)).loadAs(new ByteArrayInputStream(ymlByteArray), YamlConfig.class);
9 }
10}
YmlByteArrayDataSource继承了ShardingDataSource,调用了super方法,创建一个dataSource,
YamlConfig继承了ShardingRuleConfig , 因此unmarshal方法就是读取yaml文件,然后构建一个ShardingRuleConfig 对象用来创建ShardingDataSource
yaml配置如下
1dataSource:
2 ds_0: !!org.apache.commons.dbcp.BasicDataSource # 数据源连接池类型。
3 driverClassName: com.mysql.jdbc.Driver # 数据库驱动
4 url: jdbc:mysql://localhost:3306/ds_yaml_0 # 地址
5 username: root # 用户名
6 password: # 密码
7 ds_1: !!org.apache.commons.dbcp.BasicDataSource
8 driverClassName: com.mysql.jdbc.Driver
9 url: jdbc:mysql://localhost:3306/ds_yaml_1
10 username: root
11 password:
12
13tables: # 分表规则
14 t_order: # 表的别称,用来写SQL,sharding-jdbc会用这个来查找真实的数据库表
15 actualTables: t_order_${0..1} # 真实的数据库表
16 tableStrategy: # 分表策略
17 shardingColumns: order_id # 分片ID
18 algorithmExpression: t_order_${order_id.longValue() % 2} # 分片策略
19
20 t_order_item: # 和t_order的一样的意义
21 actualTables: t_order_item_${0..1}
22 #绑定表中其余的表的策略与第一张表的策略相同
23 tableStrategy:
24 shardingColumns: order_id
25 algorithmExpression: t_order_item_${order_id.longValue() % 2}
26
27bindingTables:
28 - tableNames: t_order,t_order_item
29
30#默认数据库分片策略
31defaultDatabaseStrategy:
32 shardingColumns: user_id # 使用user_id 来分库
33 algorithmExpression: ds_${user_id.longValue() % 2}
34
35props:
36 sql.show: false # 是否显示SQL
上面的yaml配置一一对应ShardingRuleConfig里面的属性 .。
1public class ShardingRuleConfig {
2 private Map<String, DataSource> dataSource = new HashMap();
3 private String defaultDataSourceName;
4 private Map<String, TableRuleConfig> tables = new HashMap();
5 private List<BindingTableRuleConfig> bindingTables = new ArrayList();
6 private StrategyConfig defaultDatabaseStrategy;
7 private StrategyConfig defaultTableStrategy;
8 private String keyGeneratorClass;
9}
spring boot 硬编码配置数据源
1private static ShardingDataSource getShardingDataSource() throws SQLException {
2 // 构造DataSourceRule,即key与数据源的KV对;
3 DataSourceRule dataSourceRule = new DataSourceRule(createDataSourceMap());
4 // 建立逻辑表是t_order,实际表是t_order_0,t_order_1的TableRule
5 TableRule orderTableRule = TableRule.builder("t_order").
6 actualTables(Arrays.asList("t_order_0", "t_order_1")).dataSourceRule(dataSourceRule).build();
7 // 建立逻辑表是t_order_item,实际表是t_order_item_0,t_order_item_1的TableRule
8 TableRule orderItemTableRule = TableRule.builder("t_order_item").
9 actualTables(Arrays.asList("t_order_item_0", "t_order_item_1")).
10 dataSourceRule(dataSourceRule).build();
11 ShardingRule shardingRule = ShardingRule.builder()
12 .dataSourceRule(dataSourceRule)
13 .tableRules(Arrays.asList(orderTableRule, orderItemTableRule))
14 // 增加绑定表--绑定表代表一组表,这组表的逻辑表与实际表之
15 // 间的映射关系是相同的。比如t_order与t_order_item就是这样一组绑定表关系,它们的分库与 // 分表策略是完全相同的,那么可以使用它们的表规则将它们配置成绑定表,
16 // 绑定表所有路由计算将会只使用主表的策略;
17 .bindingTableRules(Collections.singletonList(new BindingTableRule(Arrays.asList(orderTableRule, orderItemTableRule))))
18 // 指定数据库sharding策略--根据user_id字段的值取模
19 .databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
20 // 指定表sharding策略--根据order_id字段的值取模
21 .tableShardingStrategy(new TableShardingStrategy("order_id", new ModuloTableShardingAlgorithm())).build();
22 return new ShardingDataSource(shardingRule);
23}
24
25// 创建两个数据源,一个是ds_jdbc_0,一个是ds_jdbc_1,并绑定映射关系key
26private static Map<String, DataSource> createDataSourceMap() {
27 Map<String, DataSource> result = new HashMap<>(2);
28 result.put("ds_jdbc_0", createDataSource("ds_jdbc_0"));
29 result.put("ds_jdbc_1", createDataSource("ds_jdbc_1"));
30 return result;
31}
32
33// 以dbcp组件创建一个数据源
34private static DataSource createDataSource(final String dataSourceName) {
35 BasicDataSource result = new BasicDataSource();
36 result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
37 result.setUrl(String.format("jdbc:mysql://localhost:3306/%s", dataSourceName));
38 result.setUsername("root");
39 // sharding-jdbc默认以密码为空的root用户访问,如果修改了root用户的密码,这里修改为真实的密码即可;
40 result.setPassword("");
41 return result;
42}
spring xml 方式
1 <!--配置数据源1-->
2 <bean id="ds_0" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
3 <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
4 <property name="url" value="jdbc:mysql://localhost:3306/ds_0"/>
5 <property name="username" value="root"/>
6 <property name="password" value=""/>
7 </bean>
8 <!--配置数据源2-->
9 <bean id="ds_1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
10 <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
11 <property name="url" value="jdbc:mysql://localhost:3306/ds_1"/>
12 <property name="username" value="root"/>
13 <property name="password" value=""/>
14 </bean>
15 <!--配置分库策略-->
16 <rdb:strategy id="databaseShardingStrategy" sharding-columns="user_id" algorithm-class="com.dangdang.ddframe.rdb.sharding.example.jdbc.algorithm.SingleKeyModuloDatabaseShardingAlgorithm"/>
17 <!--配置分表策略-->
18 <rdb:strategy id="tableShardingStrategy" sharding-columns="order_id" algorithm-class="com.dangdang.ddframe.rdb.sharding.example.jdbc.algorithm.SingleKeyModuloTableShardingAlgorithm"/>
19 <!--构建shardingDataSource-->
20 <rdb:data-source id="shardingDataSource">
21 <!--设置数据源-->
22 <rdb:sharding-rule data-sources="ds_0, ds_1">
23 <!--设置分表规则,逻辑表和真实表的对应关系以及分库分表的策略-->
24 <rdb:table-rules>
25 <rdb:table-rule logic-table="t_order" actual-tables="t_order_${0..1}" database-strategy="databaseShardingStrategy" table-strategy="tableShardingStrategy">
26 <rdb:generate-key-column column-name="order_id"/>
27 </rdb:table-rule>
28 </rdb:table-rules>
29 </rdb:sharding-rule>
30 </rdb:data-source>
31 <!--设置事物管理器对应的dataSource为ShardingDataSource -->
32 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
33 <property name="dataSource" ref="shardingDataSource" />
34 </bean>
35 <tx:annotation-driven transaction-manager="transactionManager" />
以上是关于1.sharding-jdbc系列之 数据源配置的主要内容,如果未能解决你的问题,请参考以下文章
MySQL 数据库MySQL 主从复制和 Sharding-JDBC 实现读写分离
MySQL 数据库MySQL 主从复制和 Sharding-JDBC 实现读写分离