集成sharding-jdbc实现分库分表
sharding-jdbc
是由当当捐入给apache
的一款分布式数据库中间件,支持垂直分库、垂直分表、水平分库、水平分表、读写分离、分布式事务和高可用等相关功能。
1、ruoyi-framework\pom.xml
模块添加sharding-jdbc整合依赖
<!-- sharding-jdbc分库分表 -->
<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>sharding-jdbc-core</artifactId><version>4.1.1</version>
</dependency>
2、创建两个测试数据库
create database `ry-order1`;
create database `ry-order2`;
3、创建两个测试订单表
-- ----------------------------
-- 订单信息表sys_order_0
-- ----------------------------
drop table if exists sys_order_0;
create table sys_order_0
(order_id bigint(20) not null comment '订单ID',user_id bigint(64) not null comment '用户编号',status char(1) not null comment '状态(0交易成功 1交易失败)',order_no varchar(64) default null comment '订单流水',primary key (order_id)
) engine=innodb comment = '订单信息表';-- ----------------------------
-- 订单信息表sys_order_1
-- ----------------------------
drop table if exists sys_order_1;
create table sys_order_1
(order_id bigint(20) not null comment '订单ID',user_id bigint(64) not null comment '用户编号',status char(1) not null comment '状态(0交易成功 1交易失败)',order_no varchar(64) default null comment '订单流水',primary key (order_id)
) engine=innodb comment = '订单信息表';
4、配置文件application-druid.yml
添加测试数据源
# 数据源配置
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedriverClassName: com.mysql.cj.jdbc.Driverdruid:# 主库数据源master:url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8username: rootpassword: password# 订单库1order1:enabled: trueurl: jdbc:mysql://localhost:3306/ry-order1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8username: rootpassword: password# 订单库2order2:enabled: trueurl: jdbc:mysql://localhost:3306/ry-order2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8username: rootpassword: password...................
5、下载插件相关包和代码实现覆盖到工程中
提示
下载插件相关包和代码实现ruoyi/集成sharding-jdbc实现分库分表.zip
链接: https://pan.baidu.com/s/13JVC9jm-Dp9PfHdDDylLCQ 提取码: y9jt
6、测试验证
访问http://localhost/order/add/1
入库到ry-order2
访问http://localhost/order/add/2
入库到ry-order1
同时根据订单号order_id % 2
入库到sys_order_0
或者sys_order_1