pom.xml
springboot 2.6.3的版本
XML
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.33</version>
</dependency>
application.yml
XML
server:
port: 8080
spring:
shardingsphere:
mode:
type: Standalone
repository:
type: JDBC
props:
# 禁用执行SQL用于获取表元数据
sql-show: true
# 禁用执行SQL用于获取数据库元数据
# check-table-metadata-enabled: false
datasource:
# 配置真实数据源 相当于ds0,ds1
names: ds0
ds0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/test
username: root
password: root
rules:
sharding:
tables:
#这里以student表为例
user_info:
# 表名的分片规则: # 由数据源名 + 表名组成(参考 Inline 语法规则)
actual-data-nodes: ds0.user_info_$->{1..2}
# 分布式序列策略
key-generate-strategy:
# 自增列名称,缺省表示不使用自增主键生成器
column: id
# 分布式序列算法名称
key-generator-name: snowflake
# 配置分库策略,缺省表示使用默认分库策略,以下的分片策略只能选其一:standard/complex/hint/none
# database-strategy:
# # 用于单分片键的标准分片场景
# standard:
# # 分片列名称 这里指定age作为分库键
# sharding-column: age
# # 分片算法名称
# sharding-algorithm-name: student_age_inline
# 配置分表策略,分库键class_id,分库策略student_class_id_inline
table-strategy:
standard:
sharding-column: id
sharding-algorithm-name: user_inline
# 配置分片算法
sharding-algorithms:
# 分库策略:根据age取余2
# student_age_inline:
# type: INLINE
# props:
# algorithm-expression: ds$->{age % 2}
# 分表策略:根据classid取余2
user_inline:
type: INLINE
props:
algorithm-expression: user_info_$->{id % 2 +1}
key-generators:
# 配置主键生成算法-雪花算法
snowflake:
type: SNOWFLAKE
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
接口案例
java
/**
springboot 2.6.3 集成 sharding-jdbc 5.2.1
springboot web 依赖排除 snakeyaml 原来版本 升级新版本 否则解析有问题
使用和平时相同
*/
@RequestMapping(value = "/test",method = {RequestMethod.GET})
@ResponseBody
public ResponseEntity<String> index2() {
Snowflake snowflake = IdUtil.getSnowflake();
User user = new User();
user.setId(snowflake.nextId());
user.setName("test"+user.getId());
user.setSex("male");
user.setTsDate(new Date());
userMapper.insert(user);
return ResponseEntity.ok("success");
}