Sharding-JDBC 快速入門第一課


1.  概述

ShardingSphere是一套開源的分布式數據庫中間件解決方案組成的生態圈,它由Sharding-JDBC、Sharding-Proxy和Sharding-Sidecar(計划中)這3款相互獨立的產品組成。他們均提供標准化的數據分片、分布式事務和數據庫治理功能,可適用於如Java同構、異構語言、雲原生等各種多樣化的應用場景。

ShardingSphere定位為關系型數據庫中間件,旨在充分合理地在分布式的場景下利用關系型數據庫的計算和存儲能力。

1.1.  ShardingSphere-JDBC

Sharding-JDBC 定位為輕量級 Java 框架,在 Java 的 JDBC 層提供的額外服務。它使用客戶端直連數據庫,以 jar 包形式提供服務,無需額外部署和依賴,可理解為增強版的 JDBC 驅動,完全兼容 JDBC 和各種 ORM 框架。

  • 適用於任何基於 JDBC 的 ORM 框架,如:JPA, Hibernate, Mybatis, Spring JDBC Template 或直接使用 JDBC。
  • 支持任何第三方的數據庫連接池,如:DBCP, C3P0, BoneCP, Druid, HikariCP 等。
  • 支持任意實現JDBC規范的數據庫。目前支持 MySQL,Oracle,SQLServer,PostgreSQL 以及任何遵循 SQL92 標准的數據庫。 

 

1.2.  ShardingSphere-Proxy

Sharding-Proxy 定位為透明化的數據庫代理端,提供封裝了數據庫二進制協議的服務端版本,用於完成對異構語言的支持。目前提供 MySQL 和 PostgreSQL 版本,它可以使用任何兼容 MySQL/PostgreSQL 協議的訪問客戶端(如:MySQL Command Client, MySQL Workbench, Navicat 等)操作數據,對 DBA 更加友好。

  • 向應用程序完全透明,可直接當做 MySQL/PostgreSQL 使用。
  • 適用於任何兼容 MySQL/PostgreSQL 協議的的客戶端。

1.3.  ShardingSphere-Sidecar(TODO)

Sharding-Sidecar 定位為 Kubernetes 的雲原生數據庫代理,以 Sidecar 的形式代理所有對數據庫的訪問。通過無中心、零侵入的方案提供與數據庫交互的的嚙合層,即 Database Mesh,又可稱數據庫網格。

Database Mesh 的關注重點在於如何將分布式的數據訪問應用與數據庫有機串聯起來,它更加關注的是交互,是將雜亂無章的應用與數據庫之間的交互有效的梳理。使用 Database Mesh,訪問數據庫的應用和數據庫終將形成一個巨大的網格體系,應用和數據庫只需在網格體系中對號入座即可,它們都是被嚙合層所治理的對象。 

 

1.4.  混合架構

ShardingSphere-JDBC 采用無中心化架構,適用於 Java 開發的高性能的輕量級 OLTP 應用;ShardingSphere-Proxy 提供靜態入口以及異構語言的支持,適用於 OLAP 應用以及對分片數據庫進行管理和運維的場景。

Apache ShardingSphere 是多接入端共同組成的生態圈。 通過混合使用 ShardingSphere-JDBC 和 ShardingSphere-Proxy,並采用同一注冊中心統一配置分片策略,能夠靈活的搭建適用於各種場景的應用系統,使得架構師更加自由的調整適合與當前業務的最佳系統架構。

2.  概念 & 功能

2.1. 數據分片

從性能方面來說,由於關系型數據庫大多采用B+樹類型的索引,在數據量超過閾值的情況下,索引深度的增加也將使得磁盤訪問的IO次數增加,進而導致查詢性能的下降;同時,高並發訪問請求也使得集中式數據庫成為系統的最大瓶頸。

從運維成本方面考慮,當一個數據庫實例中的數據達到閾值以上,對於DBA的運維壓力就會增大。數據備份和恢復的時間成本都將隨着數據量的大小而愈發不可控。一般來講,單一數據庫實例的數據的閾值在1TB之內,是比較合理的范圍。

垂直分片

按照業務拆分的方式稱為垂直分片,又稱為縱向拆分,它的核心理念是專庫專用。在拆分之前,一個數據庫由多個數據表構成,每個表對應着不同的業務。而拆分之后,則是按照業務將表進行歸類,分布到不同的數據庫中,從而將壓力分散至不同的數據庫。下圖展示了根據業務需要,將用戶表和訂單表垂直分片到不同的數據庫的方案。

垂直分片往往需要對架構和設計進行調整。通常來講,是來不及應對互聯網業務需求快速變化的;而且,它也並無法真正的解決單點瓶頸。垂直拆分可以緩解數據量和訪問量帶來的問題,但無法根治。如果垂直拆分之后,表中的數據量依然超過單節點所能承載的閾值,則需要水平分片來進一步處理。

水平分片 

水平分片又稱為橫向拆分。 相對於垂直分片,它不再將數據根據業務邏輯分類,而是通過某個字段(或某幾個字段),根據某種規則將數據分散至多個庫或表中,每個分片僅包含數據的一部分。 例如:根據主鍵分片,偶數主鍵的記錄放入0庫(或表),奇數主鍵的記錄放入1庫(或表),如下圖所示。 

 

水平分片從理論上突破了單機數據量處理的瓶頸,並且擴展相對自由,是分庫分表的標准解決方案。 

目標

盡量透明化分庫分表所帶來的影響,讓使用方盡量像使用一個數據庫一樣使用水平分片之后的數據庫集群,是 Apache ShardingSphere 數據分片模塊的主要設計目標。 

2.1.1.  核心概念

數據節點

數據分片的最小單元。由數據源名稱和數據表組成,例如:ds_0.t_order_0。

分片鍵

用於分片的數據庫字段,是將數據庫(表)水平拆分的關鍵字段。例:將訂單表中的訂單主鍵的尾數取模分片,則訂單主鍵為分片字段。

SQL 中如果無分片字段,將執行全路由,性能較差。

除了對單分片字段的支持,Apache ShardingSphere 也支持根據多個字段進行分片。

分片算法

通過分片算法將數據分片,支持通過=、>=、<=、>、<、BETWEEN和IN分片。分片算法需要應用方開發者自行實現,可實現的靈活度非常高。

分片策略

包含分片鍵和分片算法,由於分片算法的獨立性,將其獨立抽離。真正可用於分片操作的是分片鍵 + 分片算法,也就是分片策略。目前提供 5 種分片策略。

行表達式 

使用表達式可以簡化配置,只需要在配置中使用 ${ expression } 或 $->{ expression } 標識行表達式即可 

${begin..end} 表示范圍區間

${[unit1, unit2, unit_x]} 表示枚舉值

行表達式中如果出現連續多個 ${ expression } 或 $->{ expression } 表達式,整個表達式最終的結果將會根據每個子表達式的結果進行笛卡爾組合。

例如,${['online', 'offline']}_table${1..3} 最終會被解析為 online_table1, online_table2, online_table3, offline_table1, offline_table2, offline_table3

分布式主鍵

在分片規則配置模塊可配置每個表的主鍵生成策略,默認使用雪花算法(snowflake)生成 64bit 的長整型數據

雪花算法是由 Twitter 公布的分布式主鍵生成算法,它能夠保證不同進程主鍵的不重復性,以及相同進程主鍵的有序性。

實現原理

在同一個進程中,它首先是通過時間位保證不重復,如果時間相同則是通過序列位保證。同時由於時間位是單調遞增的,且各個服務器如果大體做了時間同步,那么生成的主鍵在分布式環境可以認為是總體有序的,這就保證了對索引字段的插入的高效性。例如 MySQL 的 Innodb 存儲引擎的主鍵。

使用雪花算法生成的主鍵,二進制表示形式包含 4 部分,從高位到低位分表為:1bit 符號位、41bit 時間戳位、10bit 工作進程位以及 12bit 序列號位。

  • 符號位(1bit)

預留的符號位,恆為零。

  • 時間戳位(41bit)

41 位的時間戳可以容納的毫秒數是 2 的 41 次冪,一年所使用的毫秒數是:365 * 24 * 60 * 60 * 1000。通過計算可知:結果約等於 69.73 年。Apache ShardingSphere的雪花算法的時間紀元從2016年11月1日零點開始,可以使用到2086年,相信能滿足絕大部分系統的要求。

  • 工作進程位(10bit)

該標志在 Java 進程內是唯一的,如果是分布式應用部署應保證每個工作進程的 id 是不同的。該值默認為 0,可通過屬性設置。

  • 序列號位(12bit)

該序列是用來在同一個毫秒內生成不同的 ID。如果在這個毫秒內生成的數量超過 4096 (2的12次冪),那么生成器會等待到下個毫秒繼續生成。

雪花算法主鍵的詳細結構見下圖:

2.1.2.  使用規范

下面列出已明確可支持的SQL種類以及已明確不支持的SQL種類,盡量讓使用者避免踩坑。 

支持項

路由至單數據節點

  • 100%全兼容(目前僅MySQL,其他數據庫完善中) 

路由至多數據節點

  • 全面支持DML、DDL、DCL、TCL和部分DAL。支持分頁、去重、排序、分組、聚合、關聯查詢(不支持跨庫關聯)。 

不支持項

路由至多數據節點

  • 不支持CASE WHEN、HAVING、UNION (ALL),有限支持子查詢。 

https://shardingsphere.apache.org/document/current/cn/features/sharding/use-norms/sql/ 

2.2.  讀寫分離

 

讀寫分離雖然可以提升系統的吞吐量和可用性,但同時也帶來了數據不一致的問題。 這包括多個主庫之間的數據一致性,以及主庫與從庫之間的數據一致性的問題。 並且,讀寫分離也帶來了與數據分片同樣的問題,它同樣會使得應用開發和運維人員對數據庫的操作和運維變得更加復雜。 下圖展現了將分庫分表與讀寫分離一同使用時,應用程序與數據庫集群之間的復雜拓撲關系。

3.  示例:水平分庫分片

引入maven依賴

<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-core</artifactId>
    <version>${sharding-sphere.version}</version>
</dependency>

或者

<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>${shardingsphere.version}</version>
</dependency>

話不多說,上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.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cjs.example</groupId>
    <artifactId>sharding-jdbc-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sharding-jdbc-demo</name>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--<dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-core</artifactId>
            <version>4.1.1</version>
        </dependency>-->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

OrderEntiry.java

package com.cjs.example.sharding.entity;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @author ChengJianSheng
 * @date 2020-06-18
 */
@Data
@Entity
@Table(name = "t_order")
public class OrderEntity implements Serializable {

    @Id
    @Column(name = "order_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long orderId;

    private Integer userId;

    private Integer status = 1;
}

OrderRepository.java

package com.cjs.example.sharding.repository;

import com.cjs.example.sharding.entity.OrderEntity;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author ChengJianSheng
 * @date 2020-06-18
 */
public interface OrderRepository extends JpaRepository<OrderEntity, Long> {
}

OrderService.java

package com.cjs.example.sharding.service;

import com.cjs.example.sharding.entity.OrderEntity;
import com.cjs.example.sharding.repository.OrderRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ChengJianSheng
 * @date 2020-06-18
 */
@Service
public class OrderService {

    @Resource
    private OrderRepository orderRepository;

    public void save(OrderEntity entity) {
        orderRepository.save(entity);
    }

}

OrderController.java

package com.cjs.example.sharding.controller;

import com.cjs.example.sharding.entity.OrderEntity;
import com.cjs.example.sharding.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ChengJianSheng
 * @date 2020-06-18
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/save")
    public String save(@RequestParam("userId") Integer userId) {
        OrderEntity entity = new OrderEntity();
        entity.setUserId(userId);
        orderService.save(entity);
        return "ok";
    }
}

啟動類

package com.cjs.example.sharding;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * http://shardingsphere.apache.org/index.html
 * https://shardingsphere.apache.org/document/legacy/4.x/document/en/manual/sharding-jdbc/
 * http://shardingsphere.apache.org/index_zh.html
 */
@SpringBootApplication(exclude = JtaAutoConfiguration.class)
public class ShardingJdbcDemoApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(ShardingJdbcDemoApplication.class, args);
    }



    @Resource
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        System.out.println(dataSource);
    }
}

最最重要的是 application.properties

# https://shardingsphere.apache.org/document/legacy/4.x/document/en/manual/sharding-jdbc/

# 配置真實數據源
spring.shardingsphere.datasource.names=ds0,ds1

# 配置第 1 個數據源
spring.shardingsphere.datasource.ds0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds0.url=jdbc:mysql://localhost:3306/ds0
spring.shardingsphere.datasource.ds0.username=root
spring.shardingsphere.datasource.ds0.password=123456

# 配置第 2 個數據源
spring.shardingsphere.datasource.ds1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds1.url=jdbc:mysql://localhost:3306/ds1
spring.shardingsphere.datasource.ds1.username=root
spring.shardingsphere.datasource.ds1.password=123456

# 配置 t_order 表規則
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=ds$->{0..1}.t_order_$->{0..1}
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.sharding-column=order_id
spring.shardingsphere.sharding.tables.t_order.table-strategy.inline.algorithm-expression=t_order_$->{order_id % 2}
spring.shardingsphere.sharding.tables.t_order.key-generator.type=SNOWFLAKE
spring.shardingsphere.sharding.tables.t_order.key-generator.column=order_id
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.sharding-column=user_id
spring.shardingsphere.sharding.tables.t_order.database-strategy.inline.algorithm-expression=ds$->{user_id % 2}

spring.shardingsphere.props.sql.show=true

工程結構

源碼: https://github.com/chengjiansheng/sharding-jdbc-demo

通過訪問http://localhost:8080/order/save?userId=xxx想數據庫中插入數據,結果確實如預期的那樣

4.  寫在最后

配置入口類:

org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration 

文檔在這里:

https://shardingsphere.apache.org/

https://shardingsphere.apache.org/document/legacy/4.x/document/en/manual/sharding-jdbc/

http://shardingsphere.apache.org/elasticjob/

寫在最最后:

雖然  ShardingSphere-JDBC (Sharding-JDBC)  提供了很多功能,但是最常用的還是分庫分表、讀寫分離,通常是一起用

https://shardingsphere.apache.org/document/legacy/4.x/document/en/manual/sharding-jdbc/configuration/config-spring-boot/

分庫分表以后,編寫SQL時有諸多限制,很多之前在單庫單表上的操作就不能用了,而且每次查詢必須帶上分片鍵,不然的話全表掃描

如果非要分表的話,不妨先考慮一下將數據存到ElasticSearch中,查詢直接走ES。或者先走ES,然后通過主鍵再去查MySQL。

總之一句話,慎重!

 


免責聲明!

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



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