文章目录
基于spring boot3 + lombok 1.18.30 + mybatis plus 3.5.5 +nacos
Spring Boot 3 整合 Sharding-JDBC 分库分表实现
根据需求,我们需要实现两个核心功能:
- 分库:将聊天记录库和用户业务库分离 (提高主业务吞吐量)
- 分表:聊天记录表按用户ID(deviceId)分为10个表 (保证单表不超过500万数据量)
下面是核心配置和业务代码实现:
Nacos配置中心配置
在Nacos中需要添加以下配置(dataId可以是application-dev.yml等):
spring:
shardingsphere:
# 数据源配置
datasource:
# 定义所有数据源名称,多个用逗号分隔
names: user_db,message_db
# 用户数据库配置
user_db:
type: com.zaxxer.hikari.HikariDataSource # 使用Hikari连接池
driver-class-name: com.mysql.cj.jdbc.Driver # MySQL驱动类
url: jdbc:mysql://localhost:3306/user_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai # 数据库连接地址
username: root # 数据库用户名
password: root # 数据库密码
# 消息数据库配置
message_db:
type: com.zaxxer.hikari.HikariDataSource # 使用Hikari连接池
driver-class-name: com.mysql.cj.jdbc.Driver # MySQL驱动类
url: jdbc:mysql://localhost:3306/message_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai # 数据库连接地址
username: root # 数据库用户名
password: root # 数据库密码
# 分片规则配置
rules:
sharding:
# 表级别的分片配置
tables:
# 逻辑表名称:sys_message
sys_message:
# 实际数据节点:由数据库名+表名表达式组成,这里表示message_db库中的sys_message_0到sys_message_9表
actual-data-nodes: message_db.sys_message_${
0..9}
# 表分片策略
table-strategy:
# 标准分片策略
standard:
sharding-column: deviceId # 分片键:使用deviceId字段进行分片
sharding-algorithm-name: sys_message_inline # 引用的分片算法名称
# 分片算法配置
sharding-algorithms:
# 与上面引用的算法名称保持一致
sys_message_inline:
type: INLINE # 算法类型:INLINE表示使用行表达式分片算法
props:
# 分片算法表达式:
# 1. 先计算deviceId的哈希值对10取模
# 2. 处理可能出现的负数情况(当哈希值为负数时,取模结果可能为负)
# 3. 确保最终结果在0-9之间,对应sys_message_0到sys_message_9表
algorithm-expression: sys_message_${
deviceId.hashCode() % 10 + 10 >= 10 ? deviceId.hashCode() % 10 : deviceId.hashCode() % 10 + 10}
Sharding-JDBC 配置类
package com.zgb.config;
import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

最低0.47元/天 解锁文章
8799

被折叠的 条评论
为什么被折叠?



