Spring Boot 3整合Spring Dynamic和Sharding JDBC最佳实践
本文将介绍如何在Spring Boot 3项目中整合Spring Dynamic数据源和Sharding JDBC,实现动态数据源切换和分库分表功能。
1. 项目依赖
首先,在pom.xml
文件中添加必要的依赖: dynamic-datasource-spring-boot3-starter
适应springboot3.0
;
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc</artifactId>
<version>5.5.0</version>
</dependency>
<!-- 华为镜像好像没有5.5.0 我是从官方maven仓库里搜索手动导包-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<version>4.3.1</version>
</dependency>
避坑
以下shardingsphere
依赖会报错会出现Implementation of JAXB-API has not been found on module path or classpath.
和 com.sun.xml.internal.bind.v2.ContextFactory
和Representer: method 'void <init>()' not found
等错误,据说5.4.2版本才可能解决,springboot3请用上面那种。
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core</artifactId>
<version>5.3.2</version>
</dependency>
2. Sharding JDBC配置
在resources
目录下创建sharding.yaml
文件:
# !!!数据源名称要和动态数据源中配置的名称一致
databaseName: test1
# 具体参看官网文档说明
dataSources:
coupon_user_db_0:
dataSourceClassName: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.jdbc.Driver
jdbcUrl: jdbc:mysql://49.121.20.174/coupon_user_db_0?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username: root
password: root
rules:
- !SHARDING
tables: # 数据分片规则配置
coupon_user: # 逻辑表名称
actualDataNodes: coupon_user_db_0.coupon_user_$->{0..9} # 由数据源名 + 表名组成(参考 Inline 语法规则)
databaseStrategy: # 分库策略,缺省表示使用默认分库策略,以下的分片策略只能选其一
none:
tableStrategy: # 分表策略
standard: # 用于单分片键的标准分片场景
shardingColumn: user_id # 分片列名称
shardingAlgorithmName: user_inline
keyGenerateStrategy:
column: id
keyGeneratorName: snowflake
keyGenerators:
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
# 分片算法配置
shardingAlgorithms:
user_inline:
type: INLINE
props:
algorithm-expression: coupon_user_$->{user_id % 10}
props:
sql-show: true
修改resources
目录下创建application.yaml
文件:
spring:
datasource:
dynamic: # 多数据源配置
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://49.121.20.174:3306/ruoyi-vue-pro?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true # MySQL Connector/J 8.X 连接的示例
username: root
password: root
test1:
driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
url: jdbc:shardingsphere:classpath:sharding.yaml
3. 代码上添加数据源注解DS(“test1”)
由于DS(“master”) 被设置为主数据源(“primary: master”),不加注解时默认主数据源,加了 DS(“test1”)则路由至Sharding,yaml管理的数据源,本文将分表数据源命名为test1
在需要使用Sharding JDBC的Service实现类上添加@DS("test1")
注解:
@Service
@DS("test1")
public class CouponUserServiceImpl implements CouponUserService {
// 实现方法
}
4. 说明
- 本文所用
spring3
和jdk17
- 我在数据库建立了
ruoyi-vue-pro
作为主数据库(主数据源),coupon_user_db_0
为sharding
管理的数据源。