SpringBoot3 整合 ShardingSphere
SpringBoot3 整合 ShardingSphere 5.5.0 过程记录
1. 引言
在使用SpringBoot3时,如果使用ShardingSphere 5.5.0以前的版本,可能会遇到与snakeyaml和jaxb依赖相关的问题。通过升级到ShardingSphere 5.5.0版本,可以解决这些问题。本文将详细记录如何在SpringBoot3中整合ShardingSphere 5.5.0,并配置分库分表。
2. Gradle 配置
首先,在build.gradle文件中添加ShardingSphere依赖,并排除不必要的模块:
1 | implementation('org.apache.shardingsphere:shardingsphere-jdbc:5.5.0') { |
3. ShardingSphere 配置
接下来,在shardingsphere.yaml中配置ShardingSphere,以下是一个示例配置:
1 | databaseName: campus |
在shardingsphere.yaml中导入配置:
1 | spring: |
4. 配置解析
数据源配置:在
dataSources部分配置数据源,这里使用HikariDataSource作为连接池,并配置了MySQL数据库连接信息。分表策略:
actualDataNodes: 定义实际的数据节点,这里将t_student表分为两个节点t_student_1和t_student_2。tableStrategy: 指定分表策略,使用standard策略,基于id列进行分表,使用名为t_student_inline的分表算法。keyGenerateStrategy: 指定主键生成策略,基于id列,使用名为snowflake的主键生成器。
分表算法:
shardingAlgorithms: 定义分表算法,t_student_inline使用INLINE类型,算法表达式为t_student_${id % 2 + 1},即根据id的取模结果决定写入哪个表。
主键生成器:
keyGenerators: 定义主键生成器,snowflake使用SNOWFLAKE类型。
调试配置:
props.sql.show: 设置为true,以便在控制台显示SQL语句,便于调试。
5. 结论
通过上述配置,可以在 SpringBoot3 项目中成功整合 ShardingSphere 5.5.0,并实现简单的分表操作。分库的配置与分表类似,只需在rules部分增加databaseStrategy配置并定义多个数据源即可。
