3. mysql集群

3.1 企业中常用的数据库解决方案

image-20220126113803316

3.2 mysql常见的几种集群方式

3.2.1 MYSQl-MMM(Master-Master Replication Manager for MySQL

MySQL-MMM 是 Master-Master Replication Manager for MySQL(mysql 主主复制管理器) 的简称, 是 Google 的开源项目(Perl 脚本) 。

MMM 基于 MySQL Replication 做的扩展架构, 主要用来监控 mysql 主主复制并做失败转移。 其原理是将真实数据库节点的IP(RIP) 映射为虚拟 IP(VIP) 集。mysql-mmm 的监管端会提供多个虚拟 IP(VIP) , 包括一个可写 VIP,多个可读 VIP, 通过监管的管理, 这些 IP 会绑定在可用 mysql 之上, 当某一台 mysql 宕机时, 监管会将 VIP迁移至其他 mysql。在整个监管过程中, 需要在 mysql 中添加相关授权用户, 以便让 mysql 可以支持监理机的维护。 授权的用户包括一个mmm_monitor 用户和一个mmm_agent用户, 如果想使用 mmm 的备份工具则还要添加一个 mmm_tools 用户。

image-20220126114321488

3.2.2 MYSQL-MHA(mysql 主主复制管理器)

MHA(Master High Availability) 目前在 MySQL 高可用方面是一个相对成熟的解决方案,由日本 DeNA 公司 youshimaton(现就职于 Facebook 公司) 开发, 是一套优秀的作为MySQL高可用性环境下故障切换和主从提升的高可用软件。在 MySQL故障切换过程中,MHA 能做到在 0~30 秒之内自动完成数据库的故障切换操作(以 2019 年的眼光来说太慢了) , 并且在进行故障切换的过程中, MHA 能在最大程度上保证数据的一致性, 以
达到真正意义上的高可用。

3.2.3 InnoDB Cluster

InnoDB Cluster 支持自动 Failover、 强一致性、 读写分离、 读库高可用、 读请求负载均衡, 横向扩展的特性, 是比较完备的一套方案。

但是部署起来复杂, 想要解决 router单点问题好需要新增组件, 如没有其他更好的方案可考虑该方案。 InnoDB Cluster 主要由 MySQL ShellMySQL RouterMySQL 服务器集群组成, 三者协同工作, 共同为MySQL 提供完整的高可用性解决方案。

MySQL Shell 对管理人员提供管理接口, 可以很方便的对集群进行配置和管理

MySQL Router 可以根据部署的集群状况自动的初始化, 是客户端连接实例。 如果有节点 down 机, 集群会自动更新配置。 集群包含单点写入多点写入两种模式。 在单主模式下, 如果主节点 down 掉, 从节点自动替换上来,MySQL Router 会自动探测, 并将客户端连接到新节点。

image-20220126155235446

3.3 Docker 安装模拟 MySQL 主从复制集群

3.3.1 下载 mysql 镜像
docker pull mysql:5.7
3.3.2 主节点创建
3.3.2.1 创建 Master 实例并启动
docker run -p 3307:3306 --name mysql-master \
-v /mydata/mysql/master/log:/var/log/mysql \
-v /mydata/mysql/master/data:/var/lib/mysql \
-v /mydata/mysql/master/conf:/etc/mysql \
-e MYSQL_ROOT_PASSWORD=root \
-d mysql:5.7

参数说明

-p 3307:3306: 将容器的 3306 端口映射到主机的 3307 端口

-v /mydata/mysql/master/conf:/etc/mysql: 将配置文件夹挂在到主机

-v /mydata/mysql/master/log:/var/log/mysql: 将日志文件夹挂载到主机

-v /mydata/mysql/master/data:/var/lib/mysql/: 将配置文件夹挂载到主机

-e MYSQL_ROOT_PASSWORD=root: 初始化 root 用户的密码

3.3.2.2 修改 master 基本配置
vim /mydata/mysql/master/conf/my.cnf

为my.cnf写入一下配置 基本上就是设置字符集

[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
skip-name-resolve

注意: skip-name-resolve 一定要加, 不然连接 mysql 会超级慢

3.3.2.3 添加 master 主从复制部分配置

为my.cnf写入一下配置

server_id=1				 #指定集群id
log-bin=mysql-bin	     #打开二进制日志功能
read-only=0       		#关闭只读,可读可写
binlog-do-db=gulimall_ums	#指定mysql的binlog日志记录哪个db
binlog-do-db=gulimall_pms
binlog-do-db=gulimall_oms
binlog-do-db=gulimall_sms
binlog-do-db=gulimall_wms
binlog-do-db=gulimall_admin
replicate-ignore-db=mysql  #用来设置不需要同步的库,此处指定的mysql系统库
replicate-ignore-db=sys
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema
3.3.2.4 重启master
docker restart mysql-master
3.3.3 从节点创建
3.3.3.1 创建 Master 实例并启动
docker run -p 3317:3306 --name mysql-slaver-01 \
-v /mydata/mysql/slaver/log:/var/log/mysql \
-v /mydata/mysql/slaver/data:/var/lib/mysql \
-v /mydata/mysql/slaver/conf:/etc/mysql \
-e MYSQL_ROOT_PASSWORD=root \
-d mysql:5.7
3.3.3.2 修改 slaver-01基本配置
vim /mydata/mysql/slaver/conf/my.cnf

为my.cnf写入一下配置 基本上就是设置字符集

[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
skip-name-resolve
3.3.3.3 添加 master 主从复制部分配置
server_id=2                  #注意此处id不能与主节点相同
log-bin=mysql-bin
read-only=1binlog-do-db=gulimall_ums
binlog-do-db=gulimall_pms
binlog-do-db=gulimall_oms
binlog-do-db=gulimall_sms
binlog-do-db=gulimall_wms
binlog-do-db=gulimall_admin
replicate-ignore-db=mysql
replicate-ignore-db=sys
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema
3.3.3.4 重启slaver-01
docker restart mysql-master
3.3.4 为 master 授权用户来他的同步数据
3.3.4.1 进入docker容器
docker exec -it mysql-master /bin/bash
3.3.4.2 进入mysql内部
mysql –uroot -p
Enter password: root
3.3.4.2.1 授权 root 可以远程访问 ( 主从无关, 为了方便我们远程连接 mysql)
#授权
grant all privileges on *.* to 'root'@'%' identified by 'root' with grant option;
#刷新权限
flush privileges;
3.3.4.2.2 添加用来同步的用户
GRANT REPLICATION SLAVE ON *.* to 'backup'@'%' identified by '123456';

backup为账号名,123456为账号密码

3.3.4.3 查看master状态

image-20220127111912773

3.3.5 为 slaver-01授权用户来他的同步数据
3.3.5.1 进入docker容器
docker exec -it mysql-slaver-01 /bin/bash
3.3.5.2 进入mysql内部
mysql –uroot -p
Enter password: root
3.3.5.2.1 授权 root 可以远程访问 ( 主从无关, 为了方便我们远程连接 mysql)
#授权
grant all privileges on *.* to 'root'@'%' identified by 'root' with grant option;
#刷新权限
flush privileges;
3.3.5.2.2 设置主库连接
change master to master_host='192.168.157.128',master_user='backup',master_password='123456',master_log_file='mysql-bin.000001',master_log_pos=0,master_port=3307;

master_host:主节点虚拟机ip

master_user:用于连接主机的集群账号

master_password:用于连接主机的集群密码

master_log_file必须与3.3.4.3的File字段一致,Position不用一致后面会自动同步

3.3.5.2.3 启用主从同步
start slave;
3.3.5.3 查看从库状态
show slave status

image-20220127134312608

3.4 主从同步测试

主节点新建数据库gulimall_admin,从机刷新后也有相同数据库,只要此处同步其实就代表成功了

image-20220127134812174

在主节点执行gulimall_admin.sql文件

image-20220127114709649

主节点的表结构与数据也同步过来了

image-20220127135008622

3.5 mysql主从配置总结

  1. 主从数据库在自己配置文件中声明需要同步哪个数据库, 忽略哪个数据库等信息。并且 server-id 不能一样
  2. 主库授权某个账号密码来同步自己的数据
  3. 从库使用这个账号密码连接主库来同步数据

3.6 mysql分库,分表,读写分离(shardingsphere)

Apache ShardingSphere 产品定位为 Database Plus,旨在构建异构数据库上层的标准和生态。 它关注如何充分合理地利用数据库的计算存储能力,而并非实现一个全新的数据库。ShardingSphere 站在数据库的上层视角,关注他们之间的协作多于数据库自身。

连接增量可插拔是 Apache ShardingSphere 的核心概念。

  • 连接:通过对数据库协议、SQL 方言以及数据库存储的灵活适配,快速的连接应用与多模式的异构数据库;
  • 增量:获取数据库的访问流量,并提供流量重定向(数据分片、读写分离、影子库)、流量变形(数据加密、数据脱敏)、流量鉴权(安全、审计、权限)、流量治理(熔断、限流)以及**流量分析(服务质量分析、可观察性)**等透明化增量功能;
  • 可插拔:项目采用微内核 + 三层可插拔模型,使内核、功能组件以及生态对接完全能够灵活的方式进行插拔式扩展,开发者能够像使用积木一样定制属于自己的独特系统。

Apache ShardingSphere 由 JDBCProxySidecar(规划中)这 3 款既能够独立部署,又支持混合部署配合使用的产品组成。 它们均提供标准化的基于数据库作为存储节点的增量功能,可适用于如 Java 同构、异构语言、云原生等各种多样化的应用场景。

3.6.1 shardingsphere三大组件
3.6.1.1 ShardingSphere-JDBC

定位为轻量级 Java 框架,在 Java 的 JDBC 层提供的额外服务。 它使用客户端直连数据库,以 jar 包形式提供服务,无需额外部署和依赖,可理解为增强版的 JDBC 驱动,完全兼容 JDBC 和各种 ORM 框架。

  • 适用于任何基于 JDBC 的 ORM 框架,如:JPA, Hibernate, Mybatis, Spring JDBC Template 或直接使用 JDBC;
  • 支持任何第三方的数据库连接池,如:DBCP, C3P0, BoneCP, HikariCP 等;
  • 支持任意实现 JDBC 规范的数据库,目前支持 MySQL,PostgreSQL,Oracle,SQLServer 以及任何可使用 JDBC 访问的数据库。

ShardingSphere-JDBC Architecture

3.6.1.2 ShardingSphere-Proxy

定位为透明化的数据库代理端,提供封装了数据库二进制协议的服务端版本,用于完成对异构语言的支持。 目前提供 MySQL 和 PostgreSQL(兼容 openGauss 等基于 PostgreSQL 的数据库)版本,它可以使用任何兼容 MySQL/PostgreSQL 协议的访问客户端(如:MySQL Command Client, MySQL Workbench, Navicat 等)操作数据,对 DBA 更加友好。

  • 向应用程序完全透明,可直接当做 MySQL/PostgreSQL 使用;
  • 适用于任何兼容 MySQL/PostgreSQL 协议的的客户端。

ShardingSphere-Proxy Architecture

3.6.1.3 ShardingSphere-Sidecar(TODO)

定位为 Kubernetes 的云原生数据库代理,以 Sidecar 的形式代理所有对数据库的访问。 通过无中心、零侵入的方案提供与数据库交互的啮合层,即 Database Mesh,又可称数据库网格。

Database Mesh 的关注重点在于如何将分布式的数据访问应用与数据库有机串联起来,它更加关注的是交互,是将杂乱无章的应用与数据库之间的交互进行有效地梳理。 使用 Database Mesh,访问数据库的应用和数据库终将形成一个巨大的网格体系,应用和数据库只需在网格体系中对号入座即可,它们都是被啮合层所治理的对象。

ShardingSphere-Sidecar Architecture

3.6.1.4 对比(独立部署)
ShardingSphere-JDBCShardingSphere-ProxyShardingSphere-Sidecar
数据库任意MySQL/PostgreSQLMySQL/PostgreSQL
连接消耗数
异构语言仅 Java任意任意
性能损耗低损耗略高损耗低
无中心化
静态入口
3.6.1.5 混合架构

ShardingSphere-JDBC 采用无中心化架构,与应用程序共享资源,适用于 Java 开发的高性能的轻量级 OLTP 应用; ShardingSphere-Proxy 提供静态入口以及异构语言的支持,独立于应用程序部署,适用于 OLAP 应用以及对分片数据库进行管理和运维的场景。

Apache ShardingSphere 是多接入端共同组成的生态圈。 通过混合使用 ShardingSphere-JDBC 和 ShardingSphere-Proxy,并采用同一注册中心统一配置分片策略,能够灵活的搭建适用于各种场景的应用系统,使得架构师更加自由地调整适合于当前业务的最佳系统架构。

ShardingSphere Hybrid Architecture

3.6.1.6 解决方案
解决方案/功能分布式数据库数据安全数据库网关全链路压测
数据分片数据加密异构数据库支持影子库
读写分离行级权限(TODO)SQL 方言转换(TODO)可观测性
分布式事务SQL 审计(TODO)
弹性伸缩SQL 防火墙(TODO)
高可用
3.6.2 ShardingSphere-Proxy实现分库分表,读写分离

image-20220127152338488

3.6.2.1 下载 ShardingSphere-Proxy 的最新发行版。

ShardingSphere-Proxy历史版本下载地址

此处我使用的4.1.1版本老师使用的4.0.0版本我没有找到

3.6.2.2 数据库驱动-jdbc下载

mysql-jdbc下载地址

将 MySQL 的 JDBC 驱动程序复制至目录 lib目录下。

3.6.2.3 修改配置文件

解压缩后修改 conf/server.yaml 和以 config- 前缀开头的文件,如:conf/config-xxx.yaml 文件,进行分片规则、读写分离规则配置。配置方式请参考配置手册

3.6.2.3.1 配置认证信息(server.yaml)

可配置注册中心,认证信息,及一些共有属性

authentication:
  users:
    root:
      password: root
    sharding:
      password: sharding 
      authorizedSchemas: sharding_db

props:
#  max.connections.size.per.query: 1
#  acceptor.size: 16  # The default value is available processors count * 2.
  executor.size: 16  # Infinite by default.
#  proxy.frontend.flush.threshold: 128  # The default value is 128.
#    # LOCAL: Proxy will run with LOCAL transaction.
#    # XA: Proxy will run with XA transaction.
#    # BASE: Proxy will run with B.A.S.E transaction.
#  proxy.transaction.type: LOCAL
#  proxy.opentracing.enabled: false
#  proxy.hint.enabled: false
#  query.with.cipher.column: true
  sql.show: true
#  allow.range.query.with.inline.sharding: false

image-20220207155520956

3.6.2.3.2 分库分表配置(conf/config-sharding.yaml)

配置mysql的分库分表策略

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

######################################################################################################
# 
# Here you can configure the rules for the proxy.
# This example is configuration of sharding rule.
#   
# If you want to use sharding, please refer to this file; 
# if you want to use master-slave, please refer to the config-master_slave.yaml.
# 
######################################################################################################
#
#schemaName: sharding_db
#
#dataSources:
#  ds_0:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_0?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#  ds_1:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_1?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#
#shardingRule:
#  tables:
#    t_order:
#      actualDataNodes: ds_${0..1}.t_order_${0..1}
#      tableStrategy:
#        inline:
#          shardingColumn: order_id
#          algorithmExpression: t_order_${order_id % 2}
#      keyGenerator:
#        type: SNOWFLAKE
#        column: order_id
#    t_order_item:
#      actualDataNodes: ds_${0..1}.t_order_item_${0..1}
#      tableStrategy:
#        inline:
#          shardingColumn: order_id
#          algorithmExpression: t_order_item_${order_id % 2}
#      keyGenerator:
#        type: SNOWFLAKE
#        column: order_item_id
#  bindingTables:
#    - t_order,t_order_item
#  defaultDatabaseStrategy:
#    inline:
#      shardingColumn: user_id
#      algorithmExpression: ds_${user_id % 2}
#  defaultTableStrategy:
#    none:

######################################################################################################
#
# If you want to connect to MySQL, you should manually copy MySQL driver to lib directory.
#
######################################################################################################

schemaName: sharding_db

dataSources:   #数据源配置
  ds_0:
    url: jdbc:mysql://192.168.157.128:3307/demo_ds_0?serverTimezone=UTC&useSSL=false
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50
  ds_1:
    url: jdbc:mysql://192.168.157.128:3307/demo_ds_1?serverTimezone=UTC&useSSL=false
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50

shardingRule:  #分片规则
  tables:      #针对那几张表
    t_order:
      actualDataNodes: ds_${0..1}.t_order_${0..1}       #真实的数据节点对应上面配置的数据源
      tableStrategy:                                    #分库策略
        inline:                                                             
          shardingColumn: order_id                      #根据什么字段
          algorithmExpression: t_order_${order_id % 2}  #分片算法
      keyGenerator:                                     #主键生成策略
        type: SNOWFLAKE                                 #类型
        column: order_id                                #主键字段
    t_order_item:
      actualDataNodes: ds_${0..1}.t_order_item_${0..1}
      tableStrategy:
        inline:
          shardingColumn: order_id
          algorithmExpression: t_order_item_${order_id % 2}
      keyGenerator:
        type: SNOWFLAKE
        column: order_item_id
  bindingTables:        #绑定表,即分片规则一致的关系表,互为绑定表关系。绑定表之间的多表关联查询不会出现笛卡尔积关联,可以提升关联查询效率。
    - t_order,t_order_item
  defaultDatabaseStrategy:                              #默认分库策略
    inline:
      shardingColumn: user_id
      algorithmExpression: ds_${user_id % 2}
  defaultTableStrategy:                                 #默认分表策略
    none:

注意事项

image-20220207103902444

3.6.2.3.3 主从读写分离配置(conf/config-master_slave.yaml)

配置两主两从

config-master_slave.yaml改名config-master_slave1.yaml,再复制config-master_slave2.yaml

config-master_slave1.yaml

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

######################################################################################################
#
# Here you can configure the rules for the proxy.
# This example is configuration of master-slave rule.
#
# If you want to use master-slave, please refer to this file;
# if you want to use sharding, please refer to the config-sharding.yaml.
#
######################################################################################################
#
#schemaName: master_slave_db
#
#dataSources:
#  master_ds:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_master?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#  slave_ds_0:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_slave_0?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#  slave_ds_1:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_slave_1?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#
#masterSlaveRule:
#  name: ms_ds
#  masterDataSourceName: master_ds
#  slaveDataSourceNames:
#    - slave_ds_0
#    - slave_ds_1

######################################################################################################
#
# If you want to connect to MySQL, you should manually copy MySQL driver to lib directory.
#
######################################################################################################

schemaName: sharding_db_2

dataSources:
  master_0_ds:
    url: jdbc:mysql://192.168.157.128:3307/demo_ds_0?serverTimezone=UTC&useSSL=false
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50
  slave_ds_0:
    url: jdbc:mysql://192.168.157.128:3317/demo_ds_0?serverTimezone=UTC&useSSL=false
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50
    
masterSlaveRule:
  name: ms_ds
  masterDataSourceName: master_0_ds
  slaveDataSourceNames:
    - slave_ds_0
#    - slave_ds_1
  loadBalanceAlgorithmType: ROUND_ROBIN

config-master_slave2.yaml

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

######################################################################################################
#
# Here you can configure the rules for the proxy.
# This example is configuration of master-slave rule.
#
# If you want to use master-slave, please refer to this file;
# if you want to use sharding, please refer to the config-sharding.yaml.
#
######################################################################################################
#
#schemaName: master_slave_db
#
#dataSources:
#  master_ds:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_master?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#  slave_ds_0:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_slave_0?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#  slave_ds_1:
#    url: jdbc:postgresql://127.0.0.1:5432/demo_ds_slave_1?serverTimezone=UTC&useSSL=false
#    username: postgres
#    password: postgres
#    connectionTimeoutMilliseconds: 30000
#    idleTimeoutMilliseconds: 60000
#    maxLifetimeMilliseconds: 1800000
#    maxPoolSize: 50
#
#masterSlaveRule:
#  name: ms_ds
#  masterDataSourceName: master_ds
#  slaveDataSourceNames:
#    - slave_ds_0
#    - slave_ds_1

######################################################################################################
#
# If you want to connect to MySQL, you should manually copy MySQL driver to lib directory.
#
######################################################################################################

schemaName: sharding_db_1

dataSources:    
  master_1_ds:
    url: jdbc:mysql://192.168.157.128:3307/demo_ds_1?serverTimezone=UTC&useSSL=false
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50
  slave_ds_1:
    url: jdbc:mysql://192.168.157.128:3317/demo_ds_1?serverTimezone=UTC&useSSL=false
    username: root
    password: root
    connectionTimeoutMilliseconds: 30000
    idleTimeoutMilliseconds: 60000
    maxLifetimeMilliseconds: 1800000
    maxPoolSize: 50

masterSlaveRule:
  name: ms_ds
  masterDataSourceName: master_1_ds
  slaveDataSourceNames:
#    - slave_ds_0
    - slave_ds_1
  loadBalanceAlgorithmType: ROUND_ROBIN

启动测试

出现以下日志信息,代表没有找到对应的数据源信息,只需要创建对应数据库即可

image-20220207114856649

3.6.2.3.4 新增主从复制关联数据库

修改主节点配置

vim /mydata/mysql/master/conf/my.cnf
#新增以下配置
binlog-do-db=demo_ds_0
binlog-do-db=demo_ds_1

修改从节点配置

vim /mydata/mysql/slaver/conf/my.cnf
#新增以下配置
binlog-do-db=demo_ds_0
binlog-do-db=demo_ds_1

重启mysql集群

docker restart mysql-master mysql-slaver-01

在主节点新建数据库demo_ds_0 demo_ds_1,因为之前配置的主从复制在从节点中也会增加两个对应的数据库

image-20220207141040928

image-20220207141138072

3.6.2.3.5 启动连接测试

启动成功

image-20220207155651890

指定端口启动

C:\Users\eric\Desktop\apache-shardingsphere-4.1.1-sharding-proxy-bin\bin>start.bat 3388
3.6.2.3.6 Navicat天坑注意

使用Navicat连接测试

此处我遇到了一个天坑要注意,我可以正常使用Navicat连上代理,但是就是有问题,jdbc驱动换了5.1.47和8.0.11都不行,推测是我的Navicat版本和老师的不一样

image-20220208092806538

image-20220208092921072

最后我使用命令行的方式连接代理,就是正常的whats up,10.0.0.124是我本机地址

image-20220208093054353

3.6.2.3.7 分库分表测试

切换到sharding_db数据库

use sharding_db

创建测试表t_order

CREATE TABLE `t_order` (
`order_id` bigint(20) NOT NULL,
`user_id` int(11) NOT NULL,
`status` varchar(50) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

创建测试表t_order_item

CREATE TABLE `t_order_item` (
`order_item_id` bigint(20) NOT NULL,
`order_id` bigint(20) NOT NULL,
`user_id` int(11) NOT NULL,
`content` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`status` varchar(50) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`order_item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

t_order插入数据

INSERT INTO t_order (user_id, status) VALUES (1, 1);
INSERT INTO t_order (user_id, status) VALUES (2, 1);
INSERT INTO t_order (user_id, status) VALUES (3, 1);
INSERT INTO t_order (user_id, status) VALUES (4, 1);
INSERT INTO t_order (user_id, status) VALUES (5, 1);
INSERT INTO t_order (user_id, status) VALUES (6, 1);
INSERT INTO t_order (user_id, status) VALUES (7, 1);

查询sharding_db中t_order的数据

select * from t_order;

image-20220208101548516

查询主节点,demo_ds_0分库的t_order_0分表无数据

image-20220208101845448

查询主节点,demo_ds_0分库的t_order_1分表有三条数据

image-20220208101929959

查询主节点,demo_ds_1分库的t_order_0分表有四条数据

image-20220208102044006

查询主节点,demo_ds_1分库的t_order_1分表无数据

image-20220208102132161

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐