2020.05.05 springboot+sharding-j
2020-05-05 本文已影响0人
薛定谔的猴子
sharding-jdbc具体使用方式
一、先在pom.xml中引入依赖
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.1</version>
</dependency>
需要注意的是,此时druid不能用spring-boot-starter版本的,需要用正常的包,不然启动会报错找不到url
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
二、修改原有的数据源配置
spring:
shardingsphere:
datasource:
names: ds0
ds0:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 456123
sharding:
tables:
table_data:
actual-data-nodes: ds0.table_data$->{0..4}
table-strategy:
inline:
sharding-column: id
algorithm-expression: table_data$->{id % 5}
defaultDataSourceName: ds0
props:
sql.show: true
具体其他配置项,可参考官方文档
配置文件解释:
1、datasource支持添加多个数据库,只需在names中用逗号隔开,并在下方逐个描述即可。这里只用一个,简称为ds0
2、在tables中标注配置需要分表的数据表,现在我们需要处理的分表是table_data,范围是0到4。

- actual-data-nodes 代表分表的范围
- sharding-column 代表取模的字段,这里是id
- algorithm-expression 代表分表的规则,这里是是对id取模,取模因子是5
三、mybatis对分表的查询
因为数据源改用sharding-jdbc,并配置table_data为table_data$->{0..4},因此在查询语句中,直接使用table_data作为查询表明即可。例如:
1、查询语句,代表查询table_data$->{0..4}四个表
SELECT * FROM table_data