
需求说明我的系统中有一个记录表是用来记录第三方系统发送过来的数据的这个表只做记录由于有一定的数据量故考虑做分表策略提升存储和查询的效率。技术选型我想要达到功能实现简单又能做到零侵入代码逻辑的效果所以选择shardingsphere又因为项目jdk版本为1.8springboot为2.6.13所以选择整合4.1.1版本比较合适5.3.2是最后一个支持springboot2的版本但我不建议使用5.3.2版本最好还可以选择5.1.2和5.2.1因为5.3.2没有适配自动装配集成起来比较费事。版本确定接下来就看整合过程了。另外我还写了一篇整合达梦数据库的整合达梦数据库可以查看这篇SpringBoot整合ShardingSphere达梦数据库8分表经验分享分库分表策略分片策略经验分享-CSDN博客一、依赖引入首先引入包sharding-jdbc-spring-boot-starterdependency groupIdorg.apache.shardingsphere/groupId artifactIdsharding-jdbc-spring-boot-starter/artifactId version4.1.1/version /dependency二、配置配置文件配置文件中的its-decl是我的mysql的数据库名称receive_record是我要分表的具体的表spring.shardingsphere.datasource.namesits-decl #配置第一个数据源具体内容包含连接池驱动地址用户名和密码 spring.shardingsphere.datasource.its-decl.typecom.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.its-decl.driver-class-namecom.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.its-decl.urljdbc:mysql://192.168.0.23:3306/its-decl?characterEncodingutf-8useSSLfalseserverTimezoneUTC spring.shardingsphere.datasource.its-decl.usernameroot spring.shardingsphere.datasource.its-decl.password123456 #对回执记录表做分表receive_record #数据库分片策略配置指定分片的列为id根据id的值决定存放在哪个表中 spring.shardingsphere.sharding.default-database-strategy.inline.sharding-columnid #这里是配置数据按照什么算法表达式分片存放这里写死因为没有分库有分库的写法为its-decl_$-{id.hashCode().abs() % 2} spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expressionits-decl #定义逻辑表receive_record对应的两个实际的物理表的节点信 #定义 4 个实际表节点receive_record_0, receive_record_1, receive_record_2, receive_record_3 spring.shardingsphere.sharding.tables.receive_record.actual-data-nodesits-decl.receive_record_$-{0..3} #定义用于分片的列为id spring.shardingsphere.sharding.tables.receive_record.table-strategy.inline.sharding-columnid #定义分片算法这里是根据id的hashcode取模将id的hashcode对2取模将结果作为分片的结果 spring.shardingsphere.sharding.tables.receive_record.table-strategy.inline.algorithm-expressionreceive_record_$-{id.hashCode().abs() % 4} #开启打印sqltrue开启false关闭 spring.shardingsphere.props.sql.showfalse这样就整完了哈哈没错就是这么简单下面说一些注意事项吧要不然小白很不容易理解。三、注意事项1、数据表数据的表应该怎么创建呢就像我这样创建几张后缀递增的表即可说明一下因为我配置文件中用的是表达式algorithm-expressionreceive_record_$-{id.hashCode().abs() % 4}它的意思是根据表的id值得hash值取模如果你使用更高得版本则这里不是必须要用表达式的方式还可以指定分片算法为HASH_MODsharding-count4这样表示分4个表。2、内置的几种常用的分片算法说明MOD取模分片最常用id % 分表数HASH_MOD哈希取模字符串分片键INLINE行表达式分片inline 语法快速配置VOLUME_RANGE容量区间分片按数值区间分四、页面展示效果注意表索引列这个表索引是我在表里加的一个字段字段的值默认为表最后的数字这样是为了看到这条数据的表索引就知道这条数据存在了哪个表避免的人工核查数据时要一个表一个表的核对。