1:shardingsphere:
官方地址:https://shardingsphere.apache.org/document/legacy/4.x/document/cn/overview/
2: 具体实现:
1: 导入相关依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<!--druid依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<!--sharding-jdbc依赖-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.1</version>
</dependency>
2: application.yml配置文件:
对应sex字段为0,存入sharding1数据库,sex字段为1的,存入sharding2数据库。
id%3的结果对应放入user0,user1,user2表中
server:
port: 1200
spring:
main:
allow-bean-definition-overriding: true
## 打印执行sql
shardingsphere:
props:
sql:
show: true
datasource:
names: xm0,xm1 #两个数据源
xm0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/sharding1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: root
maxPoolSize: 100
minPoolSize: 5
xm1:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/sharding2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: root
maxPoolSize: 100
minPoolSize: 5
sharding:
default-database-strategy: #数据库
inline:
sharding-column: sex
algorithm-expression: xm${sex % 2}
tables:
user:
actual-data-nodes: xm${0..1}.user${0..2}
database-strategy: #分表策略,同分库策略
inline:
sharding-column: sex
algorithm-expression: xm${sex % 2}
table-strategy:
inline:
sharding-column: id
algorithm-expression: user${id % 3}
bindingTables:
- user
# broadcastTables: #广播表规则列表
# - t_config
defaultDataSourceName: xm1
KeyGenerator:
type: SNOWFLAKE #自增列值生成器类型,缺省表示使用默认自增列值生成器。可使用用户自定义的列值生成器或选择内置类型:SNOWFLAKE/UUID
column: id #自增列名称,缺省表示不使用自增主键生成器
mybatis-plus:
configuration:
map-underscore-to-camel-case: false
3: 创建对应数据库
数据库文件,以及其他相关文件请查看gitee地址
4:运行结果
分别对应插入对应的数据库以及表。
3:记录遇到的问题:
用到雪花算法的自增id时,自增的主键是long时报错,修改成Long即可。