一、XML文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:rdb="http://www.dangdang.com/schema/ddframe/rdb"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.dangdang.com/schema/ddframe/rdb
http://www.dangdang.com/schema/ddframe/rdb/rdb.xsd">
<rdb:strategy id="tableShardingStrategy" sharding-columns="user_id" algorithm-class="com.csdn.demo.sharding.ShardingAlgorithm"/>
<rdb:data-source id="shardingDataSource">
<rdb:sharding-rule data-sources="dataSource1,dataSource2,dataSource3,dataSource4">
<rdb:table-rules>
<rdb:table-rule logic-table="member_index" actual-tables="member_index_tbl_${[0,1,2,3,4,5,6,7,8,9]}${0..9}" table-strategy="tableShardingStrategy"/>
<rdb:table-rule logic-table="member_details" actual-tables="member_details_tbl_${[0,1,2,3,4,5,6,7,8,9]}${0..9}" table-strategy="tableShardingStrategy"/>
</rdb:table-rules>
</rdb:sharding-rule>
</rdb:data-source>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="shardingDataSource" />
</bean>
</beans>
二、属性详解
- 分库分表规则器
<rdb:strategy id="tableShardingStrategy" sharding-columns="user_id" algorithm-class="com.csdn.demo.sharding.ShardingAlgorithm"/>
- 数据源配置
(1)data-sources 为数据源,多个数据源需要使","分隔。
(2)logic-table 为逻辑表名。
(3)actual-tables 为实际表名。实际表名配置支持inline表达式。
例:
table_${0…2} 会解析成 table_0,table_1,table_2。
table_${[a,b,c]} 会被解析成 table_a,table_b,table_c。
两种表达式一起使用的时候,会采取笛卡尔积的方式:table_${[a,b]}${0…2}解析为table_a0,table_a1,table_a2,table_b0,table_b1,table_b2。
(4)table-strategy 为分库分表规则。
<rdb:data-source id="shardingDataSource">
<rdb:sharding-rule data-sources="dataSource1,dataSource2,dataSource3,dataSource4">
<rdb:table-rules>
<rdb:table-rule logic-table="member_index" actual-tables="member_index_tbl_${[0,1,2,3,4,5,6,7,8,9]}${0..9}" table-strategy="tableShardingStrategy"/>
<rdb:table-rule logic-table="member_details" actual-tables="member_details_tbl_${[0,1,2,3,4,5,6,7,8,9]}${0..9}" table-strategy="tableShardingStrategy"/>
</rdb:table-rules>
</rdb:sharding-rule>
</rdb:data-source>
- 数据源管理
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="shardingDataSource" />
</bean>