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,
總之一句話,慎重!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/160503.html
標籤:Java
上一篇:GIT本地庫基本操作-命令列
