分庫分表 5:讀寫分離



目錄:分庫分表 Sharding-JDBC從入門到精通

主題 鏈接地址
准備1: 在window安裝虛擬機集群 分布式 虛擬機 linux 環境制作 GO
准備2:在虛擬機的各個節點有 mysql centos mysql 筆記(內含vagrant mysql 鏡像)GO
分庫分表 -Sharding-JDBC- 從入門到精通 1 Sharding-JDBC 分庫、分表(入門實戰) GO
分庫分表 -Sharding-JDBC- 從入門到精通 2 Sharding-JDBC 基礎知識 GO
分庫分表 Sharding-JDBC 從入門到精通之 3 自定義主鍵、分布式雪花主鍵,原理與實戰 GO
分庫分表 -Sharding-JDBC- 從入門到精通 4 MYSQL集群主從復制,原理與實戰 GO
分庫分表 Sharding-JDBC 從入門到精通之 5 讀寫分離 實戰 GO
分庫分表 Sharding-JDBC 從入門到精通之 6 Sharding-JDBC執行原理 GO
分庫分表 Sharding-JDBC 從入門到精通之源碼 git倉庫地址GO

配置 MySQL 讀寫分離

請參考:分庫分表 -Sharding-JDBC- 從入門到精通 4

在cdh1節點的主庫創建表

在這里插入圖片描述

腳本如下:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user_0
-- ----------------------------
DROP TABLE IF EXISTS `t_user_0`;
CREATE TABLE `t_user_0`  (
  `id` bigint(20) NULL DEFAULT NULL,
  `name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

DROP TABLE IF EXISTS `t_user_1`;
CREATE TABLE `t_user_1`  (
  `id` bigint(20) NULL DEFAULT NULL,
  `name` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

確保cdh2節點的從庫也有以上兩個表:

在這里插入圖片描述

注意:主庫創建的表,會自動復制到從庫

配置 yml文件

在這里插入圖片描述

spring:
  shardingsphere:
    datasource:
      names: master0,slave0
      master0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        filters: com.alibaba.druid.filter.stat.StatFilter,com.alibaba.druid.wall.WallFilter,com.alibaba.druid.filter.logging.Log4j2Filter
        url: jdbc:mysql://cdh1:3306/user_db?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=true&serverTimezone=UTC
        password: 123456
        username: root
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
        connection-properties: druid.stat.merggSql=ture;druid.stat.slowSqlMillis=5000
      slave0:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        filters: com.alibaba.druid.filter.stat.StatFilter,com.alibaba.druid.wall.WallFilter,com.alibaba.druid.filter.logging.Log4j2Filter
        url: jdbc:mysql://cdh2:3306/user_db?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=true&serverTimezone=UTC
        password: 123456
        username: root
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
        connection-properties: druid.stat.merggSql=ture;druid.stat.slowSqlMillis=5000
    sharding:
      default-data-source-name: pr_master
      master-slave-rules:
        pr_master:
          name: master0slave0
          master-data-source-name: master0
          slave-data-source-names: slave0
      tables:
        #邏輯表的配置很重要,直接關系到路由是否能成功
        #shardingsphere會根據sql語言類型使用對應的路由印象進行路由,而logicTable是路由的關鍵字段
        t_user:
          actual-data-nodes: pr_master.t_user_$->{0..1}
          key-generate-strategy:
            column: id
            key-generator-name: snowflake
          table-strategy:
            inline:
              sharding-column: id
              algorithm-expression: t_user_$->{id % 2}
          key-generator:
            column: id
            type: SNOWFLAKE
            props:
              worker.id: 123


編寫代碼:t_user的增加和查詢方法

實體類

/*
 * Copyright 2016-2018 shardingsphere.io.
 * <p>
 * Licensed 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.
 * </p>
 */

package com.crazymaker.springcloud.sharding.jdbc.demo.entity.jpa;

import com.crazymaker.springcloud.sharding.jdbc.demo.entity.User;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "t_user")
public final class UserEntity extends User
{

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Override
    public long getUserId()
    {
        return super.getUserId();
    }

    @Column(name = "name")
    public String getName()
    {
        return super.getName();
    }
}

Dao層、Service層

請參見源碼工程

測試讀寫分離:

啟動應用,打開swagger ui:

在這里插入圖片描述

插入用戶,從控制台可以看出,發現插入到的是主庫

查詢用戶,從控制台可以看出,發現查詢到的是從庫


springcloud 高並發環境搭建環境 (收藏版)

組件 鏈接地址
windows centos 虛擬機 安裝&排坑 vagrant+java+springcloud+redis+zookeeper鏡像下載(&制作詳解))
centos mysql 安裝&排坑 centos mysql 筆記(內含vagrant mysql 鏡像)
linux kafka安裝&排坑 kafka springboot (或 springcloud ) 整合
Linux openresty 安裝 Linux openresty 安裝
【必須】Linux Redis 安裝(帶視頻) Linux Redis 安裝(帶視頻)
【必須】Linux Zookeeper 安裝(帶視頻) Linux Zookeeper 安裝, 帶視頻
Windows Redis 安裝(帶視頻) Windows Redis 安裝(帶視頻)
RabbitMQ 離線安裝(帶視頻) RabbitMQ 離線安裝(帶視頻)
ElasticSearch 安裝, 帶視頻 ElasticSearch 安裝, 帶視頻
Nacos 安裝(帶視頻) Nacos 安裝(帶視頻)
【必須】Eureka Eureka 入門,帶視頻
【必須】springcloud Config 入門,帶視頻 springcloud Config 入門,帶視頻
【必須】SpringCloud 腳手架打包與啟動 SpringCloud腳手架打包與啟動
Linux 自啟動 假死自啟動 定時自啟 Linux 自啟動 假死啟動

回到◀瘋狂創客圈

瘋狂創客圈 - Java高並發研習社群,為大家開啟大廠之門


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM