SpringBoot整合Sharding-JDBC实现分库分表

概述

什么是ShardingSphere

是一套开源的分布式数据库中间件解决方案组成的生态圈,由JDBC、Proxy和Sidecar三部分组成。其定位为关系型数据库中间件,旨在充分合理地在分布式的场景下利用关系型数据库的计算和存储能力,而并非实现一个全新的关系型数据库。更多详情请参阅ShardingSphere官网

什么是分库分表

随着时间和业务的发展,造成表里面的数据越来越多,如果再去对数据库表curd操作,很容易造成性能问题,这个时候,为了解决由于数据量过大而造成数据库性能降低的问题,常见的解决方案其一是从硬件上增加数据库服务器的存储,其二是分库分表处理。
分库分表有两种方式:垂直切分和水平切分
垂直分表:操作数据库中某张表,把这张表中的一部分字段数据存到一张新表里面,再把这张表另一部分字段数据存到另外一张表里面
垂直分库:把单一数据库按照业务进行划分,专库专表
水平分表:在同一个数据库中建立多张表,根据一定的规则划分主键ID,将不同的数据存放在多个表中
水平分库:将一张表建立在多个数据库,根据一定的规则划分主键ID,将数据平均存放到每一个库
随着数据库数据量增加,不要马上考虑做水分切分,首先考虑缓存处理,读写分离,使用索引等等方式,如果这些方式不能根本解决问题了,再考虑做水平分库和水平分表

Sharding-JDBC简介

是一个轻量级的Java框架,是增强版的JDBC驱动
主要目的是简化对分库分表之后数据相关操作
ShardingJDBC分库分表

技术栈

SpringBoot2.3.4
MyBatis-Plus3.4.0
Sharding-JDBC
HikariCP连接池

Sharding-JDBC实现水平分表

创建表

在数据库创建两张表course_1和course_2
约定规则:如果添加的主键ID是偶数把数据添加进course_1表,如果是奇数添加进course_2表

CREATE TABLE course_1 (
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name varchar(20) NULL COMMENT '课程名称',
	status TINYINT(2) DEFAULT 10 NOT NULL COMMENT '课程状态10:正常;20:异常',
	CONSTRAINT course_1_pk PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='课程表1';
CREATE TABLE course_2 (
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name varchar(20) NULL COMMENT '课程名称',
	status TINYINT(2) DEFAULT 10 NOT NULL COMMENT '课程状态10:正常;20:异常',
	CONSTRAINT course_2_pk PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='课程表2';

pom.xml中引入依赖

<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>

在application.properties中添加配置文件

server.port=8092
spring.application.name=springboot-sharding-JDBC
spring.shardingsphere.datasource.names=m1
#一个实体类对应两张表
spring.main.allow-bean-definition-overriding=true
spring.shardingsphere.datasource.m1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m1.jdbc-url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=qaz123456
#指定course表分布情况
spring.shardingsphere.sharding.tables.course.actual-data-nodes=m1.course_$->{1..2}
spring.shardingsphere.sharding.tables.course.key-generator.column=id
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE
#指定分片策略,id值偶数添加到course_1表,id值奇数添加到course_2表
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{id % 2 + 1}
#打开sql输出日志
spring.shardingsphere.props.sql.show=true

Sharding-JDBC的配置可以直接参照官网

测试

@SpringBootTest
public class ShardApplicationTest {

    @Autowired
    private CourseMapper courseMapper;

    @Test
    public void addCourse() {
        for (int i = 0; i < 10; i++) {
            Course course = new Course();
            course.setName("java" + i);
            courseMapper.insert(course);
        }
    }
}

course_1
course_2
查看数据库中course_1和course_2,主键为偶数的数据在1表,主键为奇数的数据在2表

Sharding-JDBC实现水平分库

创建表和数据库

分别创建两个数据库sharding_db_1和sharding_db_2,在两个数据库中分别创建两张表course_1和course_2

CREATE TABLE `course_1` (
  `id` bigint(20) NOT NULL COMMENT '主键ID',
  `name` varchar(20) DEFAULT NULL COMMENT '课程名称',
  `user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
  `status` tinyint(2) DEFAULT '10' COMMENT '状态10:正常;20:异常',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='课程表1';
CREATE TABLE `course_2` (
  `id` bigint(20) NOT NULL COMMENT '主键ID',
  `name` varchar(20) DEFAULT NULL COMMENT '课程名称',
  `user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
  `status` tinyint(2) DEFAULT '10' COMMENT '状态10:正常;20:异常',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='课程表2'

数据库规则:user_id为偶数的数据添加到sharding_db_1数据库;为奇数的数据添加到sharding_db_2数据库
表规则:id为偶数的数据添加进course_1表;为奇数的数据添加进course_2表

application.properties中配置数据库分片规则

#分库分表
spring.shardingsphere.datasource.names=m1,m2
spring.main.allow-bean-definition-overriding=true
spring.shardingsphere.datasource.m1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m1.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=qaz123456

spring.shardingsphere.datasource.m2.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m2.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m2.username=root
spring.shardingsphere.datasource.m2.password=qaz123456
#指定数据库分表情况,数据库表分布情况
spring.shardingsphere.sharding.tables.course.actual-data-nodes=m$->{1..2}.course_$->{1..2}
spring.shardingsphere.sharding.tables.course.key-generator.column=id
spring.shardingsphere.sharding.tables.course.key-generator.type=SNOWFLAKE
#指定表分片策略
spring.shardingsphere.sharding.tables.course.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.course.table-strategy.inline.algorithm-expression=course_$->{id % 2 + 1}
#指定数据库分片策略
spring.shardingsphere.sharding.tables.course.database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.course.database-strategy.inline.algorithm-expression=m$->{user_id % 2 + 1}
#打开sql日志输出
spring.shardingsphere.props.sql.show=true

测试水平分库分表

/**
 * 测试水平分库
 */
@Test
public void addCourseDB() {
    Course course = new Course();
    course.setName("java");
    course.setUserId(101L);
    courseMapper.insert(course);
}

水平分库分表
查看数据库,数据保存在sharding_db_2库中的course_1表中

Sharding-JDBC实现垂直分库

创建数据库和表

创建数据库sharding_db_3,新建表sys_user

CREATE TABLE sys_user (
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name varchar(20) NULL COMMENT '用户名称',
	CONSTRAINT sys_user_pk PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='用户表';

application.properties中配置垂直分库规则

#垂直分库策略
spring.shardingsphere.datasource.names=m1,m2,m3
spring.main.allow-bean-definition-overriding=true
spring.shardingsphere.datasource.m1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m1.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=qaz123456

spring.shardingsphere.datasource.m2.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m2.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m2.username=root
spring.shardingsphere.datasource.m2.password=qaz123456

spring.shardingsphere.datasource.m3.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m3.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m3.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_3?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m3.username=root
spring.shardingsphere.datasource.m3.password=qaz123456

#配置用户表专库专表
spring.shardingsphere.sharding.tables.sys_user.actual-data-nodes=m$->{3}.sys_user
spring.shardingsphere.sharding.tables.sys_user.key-generator.column=id
spring.shardingsphere.sharding.tables.sys_user.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.sys_user.table-strategy.inline.sharding-column=id
spring.shardingsphere.sharding.tables.sys_user.table-strategy.inline.algorithm-expression=sys_user

测试

@Test
public void addUserDB() {
    SysUser user = new SysUser();
    user.setName("zhangsan");
    userMapper.insert(user);
}

垂直分库
查看数据,用户信息插入sharding_db_3库中的sys_user表

Sharding-JDBC操作公共表

创建表

在多个数据库(sharding_db_1/sharding_db_2/sharding_db_3)中创建相同结构的公共表

CREATE TABLE `sys_dict` (
  `id` bigint(20) NOT NULL COMMENT '主键ID',
  `dict_code` varchar(20) DEFAULT NULL COMMENT '字典编码',
  `dict_value` varchar(20) DEFAULT NULL COMMENT '字典值',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='字典表';

application.properties中配置公共表规则

#测试公共表
spring.shardingsphere.datasource.names=m1,m2,m3
spring.main.allow-bean-definition-overriding=true
spring.shardingsphere.datasource.m1.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m1.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m1.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m1.username=root
spring.shardingsphere.datasource.m1.password=qaz123456

spring.shardingsphere.datasource.m2.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m2.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m2.username=root
spring.shardingsphere.datasource.m2.password=qaz123456

spring.shardingsphere.datasource.m3.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.m3.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.m3.jdbc-url=jdbc:mysql://localhost:3306/sharding_db_3?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.m3.username=root
spring.shardingsphere.datasource.m3.password=qaz123456
#配置公共表
spring.shardingsphere.sharding.broadcast-tables=sys_dict
spring.shardingsphere.sharding.tables.sys_dict.key-generator.column=id
spring.shardingsphere.sharding.tables.sys_dict.key-generator.type=SNOWFLAKE

测试

/**
 * 测试公共表
 */
@Test
public void addDict() {
    SysDict dict = new SysDict();
    dict.setDictCode("Y");
    dict.setDictValue("正常");
    dictMapper.insert(dict);
}

测试公共表1
测试公共表2
测试公共表3
查看三个数据库中的sys_dict表,新增的数据都有

完整代码详见码云地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值