Sharding-JDBC简介
- 定位为轻量级Java框架,可理解为增强版的JDBC驱动
- 完全兼容JDBC和各种ORM框架
- 支持多种数据库,目前包括MySQL,Oracle,SQLServer和PostgreSQL。
Sharding-JDBC架构图:
Springboot集成Sharding-JDBC
1.在pom.xml文件中引入依赖
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2.设置分片规则 进行测试就发现数据分别存储到t_user0和t_user1两个表中。这里采用的事按照字段sex取模分片存储
server:
port: 8080
spring:
application:
name: shatding-springboot-mybatis
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.wl.pojo
sharding:
jdbc:
datasource:
names: ds0
# 数据源ds0
ds0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/sharding
username: root
password: root
config:
sharding:
props:
sql.show: true
tables:
t_user: #t_user表
key-generator-column-name: id #主键
actual-data-nodes: ds0.t_user${0..1} #数据节点,均匀分布
table-strategy: #分表策略
inline: #行表达式
sharding-column: sex
algorithm-expression: t_user${sex % 2} #按模运算分配
3如何集成分库又分表
server:
port: 9900
spring:
application:
name: shard-jdbc-starter
# mybatis
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.wl.pojo
###数据源名称,多数据源以逗号分隔
sharding:
jdbc:
datasource:
names: ds0,ds1
# 数据源ds0
ds0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/order1
username: root
password: root
# 数据源ds1
ds1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/order2
username: root
password: root
config:
sharding:
props:
sql.show: true
tables:
t_user: #t_user表
key-generator-column-name: id #主键
actual-data-nodes: ds${0..1}.t_user${0..1} #数据节点,均匀分布
database-strategy: #分库策略
inline: #行表达式
sharding-column: city_id #列名称,多个列以逗号分隔
algorithm-expression: ds${city_id % 2} #按模运算分配
table-strategy: #分表策略
inline: #行表达式
sharding-column: sex
algorithm-expression: t_user${sex % 2}
t_address:
key-generator-column-name: id
actual-data-nodes: ds${0..1}.t_address
database-strategy:
inline:
sharding-column: lit
algorithm-expression: ds${lit % 2}