Sharding-JDBC从入门到精通(8)- 综合案例(一)数据库设计搭建与分片策略配置
一、Sharding-JDBC 综合案例-数据库设计
1、案例 需求描述:本案例实现功能如下:
- 1、添加商品
- 2、商品分页查询
- 3、商品统计
2、数据库设计
1)数据库设计如下,其中商品与店铺信息之间进行了垂直分库,分为了 PRODUCT DB(商品库) 和 STORE DB(店铺库);商品信息还进行了垂直分表,分为了商品基本信息 (product _info) 和商品描述信息 (product_descript),地理区域信息 (region) 作为公共表,冗余在两库中。
2)考虑到商品信息的数据增长性,对PRODUCT_DB(商品库)进行了水平分库,分片键使用店铺id,分片策略为店铺 ID%2 +1,因此商品描述信息对所属店铺标识进行了几余。
3)对商品基本信息(产品信息)和商品描述信息(产品描述)进行水平分表,分片键使用商品标识,分片策略为商品标识%2+1,并将为这两个表设置为绑定表,避免笛卡尔积连接。
4)为避免主键冲突,ID 生成策略采用雪花算法来生成全局唯一 ID,最终数据库设计为下图
二、Sharding-JDBC 综合案例-主从数据库搭建
1、环境说明
- 操作系统:Win10
- 数据库:MySQL-5.7.25
- JDK:64位jdk1.8.0 201
- 应用框架:spring-boot-2.1.3.RELEASE,Mybatis3.5.0
- Sharding-jDBC :sharding-jdbc-spring-boot-starter-4.0.0-RC1
2、环境准备
# 设置需要同步的数据库
binlog-do-db=store_db
binlog-do-db=product_db_1
binlog-do-db=product_db_2
2.1、mysql 主、从同步配置 (windows):新增 mysql 实例
1)复制原有 mysql (已经安装的),如: D:\mysql-5.7.25(作为主库) -> D:\mysql-5.7.25-s1(作为从库),
2)修改以下从库的 my.ini:
[mysq1d]
#设置3307端口
port =3307
# 设置mysql的安装目录
basedir=D:\mysql-5.7.25-s1
# 设置mysql数据库的数据的存放目录
datadir=D:\mysql-5.7.25-s1\data
3)安装 mysql 服务:将从库安装为 windows 服务,注意配置文件位置:
D:\mysql-5.7.25-s1\bin> mysqld install mysqls1 --defaults-file="D:\mysql-5.7.25-s1\my.ini"
4)由于从库是从主库复制过来的,因此里面的数据完全一致,可使用原来的账号、密码登录。
2.2、修改主、从库的配置文件(my.ini),新增内容如下:
1)主库配置 my.ini 文件。
[mysq1d]
#开启日志
log-bin = mysql-bin
#设置服务id,主从不能一致
server-id =1
#设置需要同步的数据库(不设置会同步所有数据库)
binlog-do-db=user_db
binlog-do-db=store_db
binlog-do-db=product_db_1
binlog-do-db=product_db_2
#屏蔽系统库同步
binlog-ignore-db=mysql
binlog-ignore-db=information_schema
binlog-ignore-db=performance_schema
2) 从库配置 my.ini 文件。
[mysq1d]
#开启日志
log-bin = mysql-bin
#设置服务id,主从不能一致
server-id =2
#设置需要同步的数据库
replicate_wild_do_table=user_db.%
replicate_wild_do_table=store_db.%
replicate_wild_do_table=product_db_1.%
replicate_wild_do_table=product_db_2.%
#屏蔽系统库同步
replicate_wild_ignore_table=mysq1.%
replicate_wild_ignore_table=information_schema.%
replicate_wild_ignore_table=performance_schema.%
2.3、重启主库和从库:
net start[主库服务名] 如: net start mysql
net start [从库服务名mysqls1] 如: net start mysqls1
请注意,主从 MySQL 下的数据(data)目录下有个文件 auto.cnf,文件中定义了 uuid,要保证主从数据库实例的 uuid 不一样,建议直接删除掉,重启服务后将会重新生成。
2.4、授权主从复制专用账号
#切换至主库 bin 目录,登录主库
mysql -h localhost -u root -p
#授权主备复制专用账号
GRANT REPLICATION SLAVE ON *.* TO 'db_sync'@'%' IDENTIFIED BY 'db_sync';
#刷新权限
FLUSH PRIVILEGES;
#确认位点记录下文件名以及位点
show master status;
2.5、设置从库向主库同步数据、并检查链路
#切换至从库bin目录,登录从库
mysql -h localhost -P3307 -uroot-p
#先停止同步
STOP SLAVE;
#修改从库指向到主库,使用上一步记录的文件名以及位点
CHANGE MASTER TO
master_host = 'localhost',
master_user = 'db_sync',
master_password = 'db_sync',
master_log_file = 'mysql-bin.000002',
master_log_pos =154;
#启动同步
START SLAVE;
#查看从库状态Slave_IO_Runing和Slave_SQL_Runing都为Yes说明同步成功,如果不为Yes,请检查error_log,然后排查相关异常。
show slave status\G
#注意 如果之前此备库已有主库指向需要先执行以下命令清空
stop slave io_thread for channel '';
reset slave all;
2.6、请注意,主从 MySQL 下的数据(data)目录下有个文件 auto.cnf,文件中定义了 uuid,要保证主从数据库实例的 uuid 不一样,建议直接删除掉,重启服务后将会重新生成。
3、初始化数据库:创建 store_db, product_db_1, product_db_2 三个数据库,并执行以下脚本创建数据表 region, store_info 和插入数据。
# 创建数据库:store_db, product_db_1, product_db_2 三个数据库。
CREATE DATABASE `store_db` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
CREATE DATABASE `product_db_1` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
CREATE DATABASE `product_db_2` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
# 在 数据库 store_db, product_db_1, product_db_2 三个数据库 中,都创建表 store_db, 并插入数据。
# 在 数据库 store_db 中,创建表 region, 并插入数据。
USE `store_db`;
# 创建 region 表
DROP TABLE IF EXISTS `region`;
CREATE TABLE `region` (
`id` BIGINT(20) NOT NULL COMMENT 'id',
`region_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地理区域编码',
`region_name` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地理区域名称',
`level` TINYINT(1) NULL DEFAULT NULL COMMENT '地理区域级别(省、市、县)',
`parent_region_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上级地理区域编码',
PRIMARY KEY(`id`) USING BTREE
) ENGINE = INNODB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
# 向 region 表中插入数据:
INSERT INTO `region` VALUES(1, '110000', '北京', 0, NULL);
INSERT INTO `region` VALUES(2, '410000', '河南', 0, NULL);
INSERT INTO `region` VALUES(3, '110100', '北京市', 1, 110000);
INSERT INTO `region` VALUES(4, '410100', '郑州市', 1, 410000);
# 在 数据库 product_db_1 中,创建表 region, 并插入数据。
USE `product_db_1`;
# 创建 region 表
DROP TABLE IF EXISTS `region`;
CREATE TABLE `region` (
`id` BIGINT(20) NOT NULL COMMENT 'id',
`region_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地理区域编码',
`region_name` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地理区域名称',
`level` TINYINT(1) NULL DEFAULT NULL COMMENT '地理区域级别(省、市、县)',
`parent_region_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上级地理区域编码',
PRIMARY KEY(`id`) USING BTREE
) ENGINE = INNODB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
# 向 region 表中插入数据:
INSERT INTO `region` VALUES(1, '110000', '北京', 0, NULL);
INSERT INTO `region` VALUES(2, '410000', '河南', 0, NULL);
INSERT INTO `region` VALUES(3, '110100', '北京市', 1, 110000);
INSERT INTO `region` VALUES(4, '410100', '郑州市', 1, 410000);
# 在 数据库 product_db_2 中,创建表 region, 并插入数据。
USE `product_db_2`;
# 创建 region 表
DROP TABLE IF EXISTS `region`;
CREATE TABLE `region` (
`id` BIGINT(20) NOT NULL COMMENT 'id',
`region_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地理区域编码',
`region_name` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地理区域名称',
`level` TINYINT(1) NULL DEFAULT NULL COMMENT '地理区域级别(省、市、县)',
`parent_region_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '上级地理区域编码',
PRIMARY KEY(`id`) USING BTREE
) ENGINE = INNODB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
# 向 region 表中插入数据:
INSERT INTO `region` VALUES(1, '110000', '北京', 0, NULL);
INSERT INTO `region` VALUES(2, '410000', '河南', 0, NULL);
INSERT INTO `region` VALUES(3, '110100', '北京市', 1, 110000);
INSERT INTO `region` VALUES(4, '410100', '郑州市', 1, 410000);
# 在 数据库 store_db 中,创建表 store_info, 并插入数据。
USE `store_db`;
# 创建 store_info 表
DROP TABLE IF EXISTS `store_info`;
DROP TABLE IF EXISTS `store info`;
CREATE TABLE `store_info` (
`id` BIGINT(20) NOT NULL COMMENT 'id',
`store_name` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '店铺名称',
`reputation` INT(11) NULL DEFAULT NULL COMMENT '信誉等级',
`region code` VARCHAR(50) CHARACTER SET Utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '店铺所在地',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = INNODB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT=DYNAMIC;
# 向表 store_info 中插入数据:
INSERT INTO `store_info` VALUES(1, 'XX零食店', 4, '110100');
INSERT INTO `store_info` VALUES(2, 'XX饮品店', 3, '410100');
三、Sharding-JDBC 综合案例-分片策略配置
1、打开 idea 创建 artifactId 名为 dbsharding 的 maven 父工程。
--> idea --> File
--> New --> Project
--> Maven
Project SDK: ( 1.8(java version "1.8.0_131" )
--> Next
--> Groupld : ( djh.it )
Artifactld : ( dbsharding )
Version : 1.0-SNAPSHOT
--> Name: ( dbsharding )
Location: ( ...\dbsharding\ )
--> Finish
2、在 dbsharding 父工程的 pom.xml 文件中导入依赖坐标。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>djh.it</groupId>
<artifactId>dbsharding</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>sharding_jdbc_simple</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>
<dependency>
<groupId>javax.interceptor</groupId>
<artifactId>javax.interceptor-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-typehandlers-jsr310</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
<!-- ...\dbsharding\pom.xml -->
3、打开 idea 创建 artifactId 名为 shopping 的 maven 子工程(子模块)。
--> idea
--> 右键 dbsharding 父工程
--> New --> Module...
--> Maven
Project SDK: ( 1.8(java version "1.8.0_131" )
--> Next
--> Groupld : ( djh.it )
Artifactld : ( shopping )
Version : 1.0-SNAPSHOT
--> Module Name: ( shopping )
Content root: ( ...\dbsharding\shopping )
Module file location: ( ...\dbsharding\shopping )
--> Finish
4、在 shopping 子工程(子模块)的 pom.xml 文件中导入依赖坐标。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>dbsharding</artifactId>
<groupId>djh.it</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>shopping</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--springfox-swagger-ui
Springfox Swagger: Spring 基于swagger规范,可以将基于SpringMVC和Spring Boot
项目的项目代码,自动生成JSON格式的描述文件。-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
</project>
<!-- dbsharding\shopping\pom.xml -->
5、在 shopping 子工程(子模块)中,创建 商品描述信息 实体 类 ProductDescript.java
/**
* dbsharding\shopping\src\main\java\djh\it\shopping\entity\ProductDescript.java
*
* 2024-7-3 创建 商品描述信息 实体 类 ProductDescript.java
*/
package djh.it.shopping.entity;
import lombok.Data;
@Data
public class ProductDescript {
private Long id;
private Long productInfoId; //所属商品id
private String descript; //商品描述
private Long storeInfoId; //店铺id
}
6、在 shopping 子工程(子模块)中,创建 商品基本信息 类 ProductInfo.java
/**
* dbsharding\shopping\src\main\java\djh\it\shopping\entity\ProductInfo.java
*
* 2024-7-3 创建 商品基本信息 类 ProductInfo.java
*/
package djh.it.shopping.entity;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class ProductInfo {
private Long productInfoId;
private Long storeInfoId; //所属店铺id
private String productName; //商品名称
private String spec; //规格
private String regionCode; //产地
private BigDecimal price; //价格
private String imageUrl; //商品图片
关联信息
private String descript; //商品描述
private String placeOfOrigin; //产地名称
private String storeName; //店铺名称
private int reputation; //店铺信誉等级
private String storeRegionNmae; //店铺地理区域名称
}
7、在 shopping 子工程(子模块)中,创建 地理区域信息 实体 类 region.java
/**
* dbsharding\shopping\src\main\java\djh\it\shopping\entity\region.java
*
* 2024-7-3 创建 地理区域信息 实体 类 region.java
*/
package djh.it.shopping.entity;
import lombok.Data;
@Data
public class region {
private Long id;
private String regionCode; //地理区域编码
private String regionNmae; //地理区域名称
}
8、在 shopping 子工程(子模块)中,创建 店铺信息 实体 类 StoreInfo.java
/**
* dbsharding\shopping\src\main\java\djh\it\shopping\entity\StoreInfo.java
*
* 2024-7-3 创建 店铺信息 实体 类 StoreInfo.java
*/
package djh.it.shopping.entity;
import lombok.Data;
@Data
public class StoreInfo {
private Long id;
private String storeName; //店铺名称
private int reputation; //信誉等级
}
9、在 shopping 子工程(子模块)中,创建 Swagger 接口定义 类 SwaggerConfiguration.java
/**
* dbsharding\shopping\src\main\java\djh\it\shopping\config\SwaggerConfiguration.java
*
* 2024-7-3 创建 Swagger 接口定义 类 SwaggerConfiguration.java
*/
package djh.it.shopping.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@ConditionalOnProperty(prefix = "swagger", value = {"enable"}, havingValue = "true" )
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket buildDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInfo())
.select()
//要扫描的API(Controller)基础包
//.apis(RequestHandlerSelectors.any()) //对所有API进行扫描
.apis(RequestHandlerSelectors //对指定包进行扫描
.basePackage("djh.it.dbsharding"))
.paths(PathSelectors.any()).build(); //对所有路径进行扫描
}
//构建API基本信息
private ApiInfo buildApiInfo(){
return new ApiInfoBuilder().title("api文档")
.description("API")
.version("1.0").build();
}
}
10、在 shopping 子工程(子模块)中,创建 启动类 SwaggerConfiguration.java
/**
* dbsharding\shopping\src\main\java\djh\it\shopping\SwaggerConfiguration.java
*
* 2024-7-3 创建 启动类 SwaggerConfiguration.java
*/
package djh.it.shopping;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ShoppingBootstrap {
public static void main( String[] args ) {
SpringApplication.run(ShoppingBootstrap.class, args);
}
}
11、在 shopping 子工程(子模块)中,创建 配置文件 application.properties 并配置 sharding-jdbc 分片规则配置
# dbsharding\shopping\src\main\resources\application.properties
server.port = 56082
spring.application.name = shopping
spring.profiles.active = local
server.servlet.context-path = /shopping
spring.http.encoding.enabled = true
spring.http.encoding.charset = utf-8
spring.http.encoding.force = true
spring.main.allow-bean-definition-overriding = true
mybatis.configuration.map-underscore-to-camel-case = true
# sharding-jdbc 分片规则配置:
# 1)配置数据源:真实数据源定义 m为主库,s为从库。m0, m1, m2, s0, s1, s2
spring.shardingsphere.datasource.names = m0,m1,m2,s0,s1,s2
spring.shardingsphere.datasource.m0.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m0.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m0.url = jdbc:mysql://localhost:3306/store_db?useUnicode=true
spring.shardingsphere.datasource.m0.username = root
spring.shardingsphere.datasource.m0.password = 12311
spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m1.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/product_db_1?useUnicode=true
spring.shardingsphere.datasource.m1.username = root
spring.shardingsphere.datasource.m1.password = 12311
spring.shardingsphere.datasource.m2.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.m2.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.m2.url = jdbc:mysql://localhost:3306/product_db_2?useUnicode=true
spring.shardingsphere.datasource.m2.username = root
spring.shardingsphere.datasource.m2.password = 12311
spring.shardingsphere.datasource.s0.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.s0.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.s0.url = jdbc:mysql://localhost:3307/store_db?useUnicode=true
spring.shardingsphere.datasource.s0.username = root
spring.shardingsphere.datasource.s0.password = 12311
spring.shardingsphere.datasource.s1.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.s1.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.s1.url = jdbc:mysql://localhost:3307/product_db_1?useUnicode=true
spring.shardingsphere.datasource.s1.username = root
spring.shardingsphere.datasource.s1.password = 12311
spring.shardingsphere.datasource.s2.type = com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.s2.driver-class-name = com.mysql.jdbc.Driver
spring.shardingsphere.datasource.s2.url = jdbc:mysql://localhost:3307/product_db_2?useUnicode=true
spring.shardingsphere.datasource.s2.username = root
spring.shardingsphere.datasource.s2.password = 12311
# 2)配置主、从关系数据库:
# 主库从库逻辑数据源定义 ds0为store_db ds1为product_db_1 ds2为product_db_2
spring.shardingsphere.sharding.master-slave-rules.ds0.master-data-source-name=m0
spring.shardingsphere.sharding.master-slave-rules.ds0.slave-data-source-names=s0
spring.shardingsphere.sharding.master-slave-rules.ds1.master-data-source-name=m1
spring.shardingsphere.sharding.master-slave-rules.ds1.slave-data-source-names=s1
spring.shardingsphere.sharding.master-slave-rules.ds2.master-data-source-name=m2
spring.shardingsphere.sharding.master-slave-rules.ds2.slave-data-source-names=s2
# 3)配置 分库策略(水平分库):
# 默认分库策略,以store_info_id为分片键,分片策略为store_info_id % 2 + 1,也就是store_info_id为双数的数据进入ds1, 为单数的进入ds2
spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column = store_info_id
spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression = ds$->{store_info_id % 2 + 1}
# 4)配置 分表策略(水平分表)
# 4.1) store_info 分表策略,固定分配至ds0的store_info真实表
spring.shardingsphere.sharding.tables.store_info.actual-data-nodes = ds$->{0}.store_info
spring.shardingsphere.sharding.tables.store_info.table-strategy.inline.sharding-column = id
spring.shardingsphere.sharding.tables.store_info.table-strategy.inline.algorithm-expression = store_info
# 4.2) product_info 分表策略
# 数据结点包括:ds1.product_info_1, ds1.product_info_2, ds2.product_info_1, ds2.product_info_2 四个节点。
spring.shardingsphere.sharding.tables.product_info.actual-data-nodes = ds$->{1..2}.product_info_$->{1..2}
# 分片策略(水平分表):分片策略为product_info_id % 2 + 1
spring.shardingsphere.sharding.tables.product_info.table-strategy.inline.sharding-column = product_info_id
spring.shardingsphere.sharding.tables.product_info.table-strategy.inline.algorithm-expression = product_info_$->{product_info_id % 2 + 1}
# 主键策略(product_info_id 生成为雪花算法,为双数的数据进入 product_info_1表,为单数的进入 product_info_2表)
spring.shardingsphere.sharding.tables.product_info.key-generator.column = product_info_id
spring.shardingsphere.sharding.tables.product_info.key-generator.type = SNOWFLAKE
# 4.3) product descript 分表策略
# 分布在 ds1,ds2 的 product_descript_1 product_descript_2表,分片策略为 product_info_id % 2 + 1,
# id 生成为雪花算法, product_info_id 为双数的数据进入 product_descript_1表,为单数的进入 product_descript_2表
spring.shardingsphere.sharding.tables.product_descript.actual-data-nodes = ds$->{1..2}.product_descript_$->{1..2}
spring.shardingsphere.sharding.tables.product_descript.table-strategy.inline.sharding-column =product_info_id
spring.shardingsphere.sharding.tables.product_descript.table-strategy.inline.algorithm-expression =product_descript_$->fproduct_info_id % 2 + 1}
spring.shardingsphere.sharding.tables.product_descript.key-generator.column=id
spring.shardingsphere.sharding.tables.product_descript.key-generator.type=SNOWFLAKE
# 5)设置 product_info,product_descript为绑定表
spring.shardingsphere.sharding.binding-tables = product_info,product_descript
# 6)设置region为广播表(公共表),每次更新操作会发送至所有数据源
spring.shardingsphere.sharding.broadcast-tables=region
# 7)打开 sql 输出日志
spring.shardingsphere.props.sql.show = true
swagger.enable = true
logging.level.root = info
logging.level.org.springframework.web = info
logging.level.djh.it.dbsharding = debug
logging.level.druid.sql = debug
上一节关联链接请点击
# Sharding-JDBC从入门到精通(7)- Sharding-JDBC 公共表 与 读写分离