欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合sharding-jdbc实现分库分表与读写分离的示例

程序员文章站 2022-03-06 15:39:15
目录一、前言二、数据库表准备三、整合四、docker-compose部署mysql主从五、本文案例demo源码一、前言本文将基于以下环境整合sharding-jdbc实现分库分表与读写分离 sp...

一、前言

本文将基于以下环境整合sharding-jdbc实现分库分表读写分离

  • springboot2.4.0
  • mybatis-plus3.4.3.1
  • mysql5.7主从

https://github.com/apache/shardingsphere

二、数据库表准备

温馨小提示:此sql执行时,如果之前有存在相应库和表会进行自动删除后再创建!

drop database if exists ds0;
create database ds0;
use ds0;

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for t_user0
-- ----------------------------
drop table if exists `t_user0`;
create table `t_user0`  (
                            `user_id` bigint(20) unsigned not null auto_increment comment '主键id',
                            `username` varchar(20) character set utf8mb4 collate utf8mb4_general_ci null default null comment '用户名',
                            `password` varchar(50) character set utf8mb4 collate utf8mb4_general_ci null default null comment '密码',
                            `sex` tinyint(4) null default null comment '性别',
                            `remark` varchar(100) character set utf8mb4 collate utf8mb4_general_ci null default null comment '备注',
                            primary key (`user_id`) using btree
) engine = innodb auto_increment = 1 character set = utf8mb4 collate = utf8mb4_general_ci comment = '用户' row_format = dynamic;

-- ----------------------------
-- table structure for t_user1
-- ----------------------------
drop table if exists `t_user1`;
create table `t_user1`  (
                            `user_id` bigint(20) unsigned not null auto_increment comment '主键id',
                            `username` varchar(20) character set utf8mb4 collate utf8mb4_general_ci null default null comment '用户名',
                            `password` varchar(50) character set utf8mb4 collate utf8mb4_general_ci null default null comment '密码',
                            `sex` tinyint(4) null default null comment '性别',
                            `remark` varchar(100) character set utf8mb4 collate utf8mb4_general_ci null default null comment '备注',
                            primary key (`user_id`) using btree
) engine = innodb auto_increment = 1 character set = utf8mb4 collate = utf8mb4_general_ci comment = '用户' row_format = dynamic;

set foreign_key_checks = 1;


-- ===============================================================================================


drop database if exists ds1;
create database ds1;
use ds1;

set names utf8mb4;
set foreign_key_checks = 0;

-- ----------------------------
-- table structure for t_user0
-- ----------------------------
drop table if exists `t_user0`;
create table `t_user0`  (
                            `user_id` bigint(20) unsigned not null auto_increment comment '主键id',
                            `username` varchar(20) character set utf8mb4 collate utf8mb4_general_ci null default null comment '用户名',
                            `password` varchar(50) character set utf8mb4 collate utf8mb4_general_ci null default null comment '密码',
                            `sex` tinyint(4) null default null comment '性别',
                            `remark` varchar(100) character set utf8mb4 collate utf8mb4_general_ci null default null comment '备注',
                            primary key (`user_id`) using btree
) engine = innodb auto_increment = 1 character set = utf8mb4 collate = utf8mb4_general_ci comment = '用户' row_format = dynamic;

-- ----------------------------
-- table structure for t_user1
-- ----------------------------
drop table if exists `t_user1`;
create table `t_user1`  (
                            `user_id` bigint(20) unsigned not null auto_increment comment '主键id',
                            `username` varchar(20) character set utf8mb4 collate utf8mb4_general_ci null default null comment '用户名',
                            `password` varchar(50) character set utf8mb4 collate utf8mb4_general_ci null default null comment '密码',
                            `sex` tinyint(4) null default null comment '性别',
                            `remark` varchar(100) character set utf8mb4 collate utf8mb4_general_ci null default null comment '备注',
                            primary key (`user_id`) using btree
) engine = innodb auto_increment = 1 character set = utf8mb4 collate = utf8mb4_general_ci comment = '用户' row_format = dynamic;

set foreign_key_checks = 1;

SpringBoot整合sharding-jdbc实现分库分表与读写分离的示例

三、整合

1、pom中引入依赖

<!-- sharding-jdbc -->
<!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-spring-boot-starter -->
<dependency>
    <groupid>org.apache.shardingsphere</groupid>
    <artifactid>sharding-jdbc-spring-boot-starter</artifactid>
    <version>4.1.1</version>
</dependency>

2、application.yml配置

spring:
  # sharding-jdbc配置
  shardingsphere:
    # 是否开启sql显示
    props:
      sql:
        show: true
    # ====================== ↓↓↓↓↓↓ 数据源配置 ↓↓↓↓↓↓ ======================
    datasource:
      names: ds-master-0,ds-slave-0-1,ds-slave-0-2,ds-master-1,ds-slave-1-1,ds-slave-1-2
      # ====================== ↓↓↓↓↓↓ 配置第1个主从库 ↓↓↓↓↓↓ ======================
      # 主库1
      ds-master-0:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.jdbc.driver
        jdbc-url: jdbc:mysql://127.0.0.1:3306/ds0?allowmultiqueries=true&useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=false # mysql在高版本需要指明是否进行ssl连接 解决则加上 &usessl=false
        username: root
        password: root
      # 主库1-从库1
      ds-slave-0-1:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.jdbc.driver
        jdbc-url: jdbc:mysql://127.0.0.1:3307/ds0?allowmultiqueries=true&useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=false # mysql在高版本需要指明是否进行ssl连接 解决则加上 &usessl=false
        username: root
        password: root
      # 主库1-从库2
      ds-slave-0-2:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.jdbc.driver
        jdbc-url: jdbc:mysql://127.0.0.1:3307/ds0?allowmultiqueries=true&useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=false # mysql在高版本需要指明是否进行ssl连接 解决则加上 &usessl=false
        username: root
        password: root
      # ====================== ↓↓↓↓↓↓ 配置第2个主从库 ↓↓↓↓↓↓ ======================
      # 主库2
      ds-master-1:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.jdbc.driver
        jdbc-url: jdbc:mysql://127.0.0.1:3306/ds1?allowmultiqueries=true&useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=false # mysql在高版本需要指明是否进行ssl连接 解决则加上 &usessl=false
        username: root
        password: root
      # 主库2-从库1
      ds-slave-1-1:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.jdbc.driver
        jdbc-url: jdbc:mysql://127.0.0.1:3307/ds1?allowmultiqueries=true&useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=false # mysql在高版本需要指明是否进行ssl连接 解决则加上 &usessl=false
        username: root
        password: root
      # 主库2-从库2
      ds-slave-1-2:
        type: com.zaxxer.hikari.hikaridatasource
        driver-class-name: com.mysql.jdbc.driver
        jdbc-url: jdbc:mysql://127.0.0.1:3307/ds1?allowmultiqueries=true&useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=false # mysql在高版本需要指明是否进行ssl连接 解决则加上 &usessl=false
        username: root
        password: root

    sharding:
      # ====================== ↓↓↓↓↓↓ 分库分表配置 ↓↓↓↓↓↓ ======================
      # 分库策略 => 根据user_id取模拆分到不同的库中
      default-database-strategy:
        inline:
          sharding-column: user_id
          algorithm-expression: ds-master-$->{user_id % 2}
      # 分表策略
      tables:
        t_user:
          actual-data-nodes: ds-master-$->{0..1}.t_user$->{0..1}
          key-generator:
            column: user_id  # 主键id
            type: snowflake  # 生成策略
          # 添加数据分表策略
          table-strategy:
            inline:
              # 添加数据分表字段(根据字段插入数据到那个表 ex:sex)
              sharding-column: sex
              # 分片算法表达式 => 根据用户性别取模拆分到不同的表中
              algorithm-expression: t_user$->{sex % 2}

      # ====================== ↓↓↓↓↓↓ 读写分离配置 ↓↓↓↓↓↓ ======================
      master-slave-rules:
        ds-master-0:
          # 主库
          masterdatasourcename: ds-master-0
          # 从库
          slavedatasourcenames:
            - ds-slave-0-1
            - ds-slave-0-2
          # 从库查询数据的负载均衡算法 目前有2种算法 round_robin(轮询)和 random(随机)
          # 算法接口 org.apache.shardingsphere.spi.masterslave.masterslaveloadbalancealgorithm
          # 实现类 randommasterslaveloadbalancealgorithm 和 roundrobinmasterslaveloadbalancealgorithm
          loadbalancealgorithmtype: round_robin
        ds-master-1:
          masterdatasourcename: ds-master-1
          slavedatasourcenames:
            - ds-slave-1-1
            - ds-slave-1-2
          loadbalancealgorithmtype: round_robin

3、引入sharding-jdbc后数据源健康配置

解决启动报错问题: connectioncallback; isvalid; nested exception is java.sql.sqlfeaturenotsupportedexception: isvalid

原因: springboot2.4数据源健康检查

@configuration
public class datasourcehealthconfig extends datasourcehealthcontributorautoconfiguration {

    @value("${spring.datasource.dbcp2.validation-query:select 1}")
    private string defaultquery;

    public datasourcehealthconfig(map<string, datasource> datasources, objectprovider<datasourcepoolmetadataprovider> metadataproviders) {
        super(datasources, metadataproviders);
    }

    @override
    protected abstracthealthindicator createindicator(datasource source) {
        datasourcehealthindicator indicator = (datasourcehealthindicator) super.createindicator(source);
        if (!stringutils.hastext(indicator.getquery())) {
            indicator.setquery(defaultquery);
        }
        return indicator;
    }
}

到此配置完成,然后就可以自己编写crud进行测试了,配置比较简单,属于入门篇

四、docker-compose部署mysql主从

# 环境准备
git clone https://gitee.com/zhengqingya/docker-compose.git
cd docker-compose/liunx
# 运行
docker-compose -f docker-compose-mysql-master-slave.yml -p mysql-master-slave up -d
# ================== ↓↓↓↓↓↓ 配置主库 ↓↓↓↓↓↓ ==================
# 进入主库
docker exec -it mysql_master /bin/bash
# 登录mysql
mysql -uroot -proot
#  创建用户slave,密码123456
create user 'slave'@'%' identified by '123456';
# 授予slave用户 `replication slave`权限和`replication client`权限,用于在`主` `从` 数据库之间同步数据
grant replication slave, replication client on *.* to 'slave'@'%';
# 授予所有权限则执行命令: grant all privileges on *.* to 'slave'@'%';
# 使操作生效
flush privileges;
# 查看状态
show master status;
# 注:file和position字段的值slave中将会用到,在slave操作完成之前不要操作master,否则将会引起状态变化,即file和position字段的值变化 !!!
# +------------------+----------+--------------+------------------+-------------------+
# | file             | position | binlog_do_db | binlog_ignore_db | executed_gtid_set |
# +------------------+----------+--------------+------------------+-------------------+
# | mysql-bin.000003 |      769 |              |                  |                   |
# +------------------+----------+--------------+------------------+-------------------+
# 1 row in set (0.00 sec)


# ================== ↓↓↓↓↓↓ 配置从库 ↓↓↓↓↓↓ ==================
# 进入从库
docker exec -it mysql_slave /bin/bash
# 登录mysql
mysql -uroot -proot
change master to master_host='www.zhengqingya.com',master_port=3306, master_user='slave', master_password='123456', master_log_file='mysql-bin.000003', master_log_pos= 769, master_connect_retry=30;
# 开启主从同步过程  【停止命令:stop slave;】
start slave;
# 查看主从同步状态
show slave status \g
# slave_io_running 和 slave_sql_running 都是yes的话,就说明主从同步已经配置好了!
# 如果slave_io_running为connecting,slavesqlrunning为yes,则说明配置有问题,这时候就要检查配置中哪一步出现问题了哦,可根据last_io_error字段信息排错或谷歌…
# *************************** 1. row ***************************
#                slave_io_state: waiting for master to send event
#                   master_host: www.zhengqingya.com
#                   master_user: slave
#                   master_port: 3306
#                 connect_retry: 30
#               master_log_file: mysql-bin.000003
#           read_master_log_pos: 769
#                relay_log_file: c598d8402b43-relay-bin.000002
#                 relay_log_pos: 320
#         relay_master_log_file: mysql-bin.000003
#              slave_io_running: yes
#             slave_sql_running: yes
#               replicate_do_db:

五、本文案例demo源码

https://gitee.com/zhengqingya/java-workspace

到此这篇关于springboot整合sharding-jdbc实现分库分表与读写分离的示例的文章就介绍到这了,更多相关springboot sharding-jdbc分库分表与读写分离内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!