1、什么是分库分表?
A:把一个数据库该分为多个,把一张表垂直或水平分割。
2、为什么要分库分表?
A:当我们的请求和数据量越来越大时,受到单机服务器的性能限制和单张表数据量的限制,已经无法满足我们的需求,我们需要多台数据库分散压力,从而提高服务的整体性能。
shardingSphere 概览:概览 :: ShardingSphere
demo项目:
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.david</groupId>
<artifactId>sharding-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sharding-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<sharding-jdbc.version>4.0.0</sharding-jdbc.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-core</artifactId>
<version>${sharding-jdbc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
OrderInfo.xml
分表算法类 在分表规则配置中使用
分表算法,sharding.xml中使用
sharding.yml 分表规则配置
sharding.yml文件创建ShardingDataSource
进入 YamlShardingDataSourceFactory,查看数据源创建方式 ,可以看到创建数据源的方式有多中;
以下代码主吧配置文件转化为java实体类:
YamlRootShardingConfiguration config = YamlEngine.unmarshal(yamlFile, YamlRootShardingConfiguration.class);
查看 YamlRootShardingConfiguration 基本有配置有以下属性:dataSources、shardingRule、props;
dataSources:数据源对应的Map集合,key为数据源名称,在sharding.xml中key为ds;
shardingRule: 分表规则配置;
props:属性配置;
yml 官方配置文档说明:Yaml配置 :: ShardingSphere
进入 ShardingDataSourceFactory
props.executor.size若不配置会创建一个Integer.MAX值的线程池队列,所以这里最好设置一下,防止线程数过多。
local:ShardingExecutorService
while 循环关闭线程池
sql打印
未完。。。