以前一篇文章中咱們講了基於Mysql8的讀寫分離(文末有連接),此次來講說分庫分表的實現過程。java
按照業務拆分的方式稱爲垂直分片,又稱爲縱向拆分,它的核心理念是專庫專用。 在拆分以前,一個數據庫由多個數據表構成,每一個表對應着不一樣的業務。而拆分以後,則是按照業務將表進行歸類,分佈到不一樣的數據庫中,從而將壓力分散至不一樣的數據庫。 下圖展現了根據業務須要,將用戶表和訂單表垂直分片到不一樣的數據庫的方案。node
垂直分片每每須要對架構和設計進行調整。一般來說,是來不及應對互聯網業務需求快速變化的;並且,它也並沒有法真正的解決單點瓶頸。 垂直拆分能夠緩解數據量和訪問量帶來的問題,但沒法根治。若是垂直拆分以後,表中的數據量依然超過單節點所能承載的閾值,則須要水平分片來進一步處理。mysql
水平分片又稱爲橫向拆分。 相對於垂直分片,它再也不將數據根據業務邏輯分類,而是經過某個字段(或某幾個字段),根據某種規則將數據分散至多個庫或表中,每一個分片僅包含數據的一部分。 例如:根據主鍵分片,偶數主鍵的記錄放入0庫(或表),奇數主鍵的記錄放入1庫(或表),以下圖所示。git
水平分片從理論上突破了單機數據量處理的瓶頸,而且擴展相對自由,是分庫分表的標準解決方案。github
分庫分表經常使用的組件就是shardingsphere,目前已是apache頂級項目,此次咱們使用springboot2.1.9 + shardingsphere4.0.0-RC2(均爲最新版本)來完成分庫分表的操做。web
假設有一張訂單表,咱們須要將它分紅2個庫,每一個庫三張表,根據id字段取模肯定最終數據的位置,數據庫環境配置以下:算法
三張表的邏輯表爲t_order,你們能夠根據建表語句準備好其餘全部數據表。spring
DROP TABLE IF EXISTS `t_order_0; CREATE TABLE `t_order_0` ( `id` bigint(20) NOT NULL, `name` varchar(255) DEFAULT NULL COMMENT '名稱', `type` varchar(255) DEFAULT NULL COMMENT '類型', `gmt_create` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '建立時間', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
注意,千萬不能將主鍵的生成規則設置成自增加,須要按照必定規則來生成主鍵,這裏使用shardingsphere中的SNOWFLAKE俗稱雪花算法來生成主鍵sql
<properties> <java.version>1.8</java.version> <mybatis-plus.version>3.1.1</mybatis-plus.version> <sharding-sphere.version>4.0.0-RC2</sharding-sphere.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.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>${sharding-sphere.version}</version> </dependency> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-namespace</artifactId> <version>${sharding-sphere.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </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>
@Configuration @MapperScan("com.github.jianzh5.blog.mapper") public class MybatisPlusConfig { /** * 攻擊 SQL 阻斷解析器 */ @Bean public PaginationInterceptor paginationInterceptor(){ PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); List<ISqlParser> sqlParserList = new ArrayList<>(); sqlParserList.add(new BlockAttackSqlParser()); paginationInterceptor.setSqlParserList(sqlParserList); return new PaginationInterceptor(); } /** * SQL執行效率插件 */ @Bean // @Profile({"dev","test"}) public PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); } }
@Data @TableName("t_order") public class Order { private Long id; private String name; private String type; private Date gmtCreate; }
/** * 訂單Dao層 */ public interface OrderMapper extends BaseMapper<Order> { }
public interface OrderService extends IService<Order> { } /** * 訂單實現層 * @author jianzh5 * @date 2019/10/15 17:05 */ @Service public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService { }
server.port=8080 # 配置ds0 和ds1兩個數據源 spring.shardingsphere.datasource.names = ds0,ds1 #ds0 配置 spring.shardingsphere.datasource.ds0.type = com.zaxxer.hikari.HikariDataSource spring.shardingsphere.datasource.ds0.driver-class-name = com.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.ds0.jdbc-url = jdbc:mysql://192.168.249.129:3306/blog?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false spring.shardingsphere.datasource.ds0.username = root spring.shardingsphere.datasource.ds0.password = 000000 #ds1 配置 spring.shardingsphere.datasource.ds1.type = com.zaxxer.hikari.HikariDataSource spring.shardingsphere.datasource.ds1.driver-class-name = com.mysql.cj.jdbc.Driver spring.shardingsphere.datasource.ds1.jdbc-url = jdbc:mysql://192.168.249.131:3306/blog?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false spring.shardingsphere.datasource.ds1.username = root spring.shardingsphere.datasource.ds1.password = 000000 # 分庫策略 根據id取模肯定數據進哪一個數據庫 spring.shardingsphere.sharding.default-database-strategy.inline.sharding-column = id spring.shardingsphere.sharding.default-database-strategy.inline.algorithm-expression = ds$->{id % 2} # 具體分表策略 # 節點 ds0.t_order_0,ds0.t_order_1,ds1.t_order_0,ds1.t_order_1 spring.shardingsphere.sharding.tables.t_order.actual-data-nodes = ds$->{0..1}.t_order_$->{0..2} # 分表字段id spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column = id # 分表策略 根據id取模,肯定數據最終落在那個表中 spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression = t_order_$->{id % 3} # 使用SNOWFLAKE算法生成主鍵 spring.shardingsphere.sharding.tables.t_order.key-generator.column = id spring.shardingsphere.sharding.tables.t_order.key-generator.type = SNOWFLAKE #spring.shardingsphere.sharding.binding-tables=t_order spring.shardingsphere.props.sql.show = true
public class OrderServiceImplTest extends BlogApplicationTests { @Autowired private OrderService orderService; @Test public void testSave(){ for (int i = 0 ; i< 100 ; i++){ Order order = new Order(); order.setName("電腦"+i); order.setType("辦公"); orderService.save(order); } } @Test public void testGetById(){ long id = 1184489163202789377L; Order order = orderService.getById(id); System.out.println(order.toString()); } }
在數據表中查看數據,確認數據正常插入 數據庫
至此分庫分表開發完成
往期回顧
歡迎關注個人我的公衆號:JAVA日知錄