分库分表 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高并发研习社群,为大家开启大厂之门

posted @ 2021-01-01 22:14  疯狂创客圈  阅读(347)  评论(0编辑  收藏  举报