最近有個項目的幾張表,數量級在千萬以上,技術棧是SpringBoot+Mybatis-plus+MySQL。如果使用單表,在進行查詢操作,非常耗時,經過一番調研,決定使用分表中間件:ShardingSphere。
ShardingSphere今年4月份成爲了 Apache 軟件基金會的頂級項目,目前支持數據分片、讀寫分離、多數據副本、數據加密、影子庫壓測等功能,同時兼容多種數據庫,通過可插拔架構,理想情況下,可以做到對業務代碼無感知。
ShardingSphere下有兩款成熟的產品:sharding jdbc和sharding proxy
- sharding jdbc:可理解爲增強版的 JDBC 驅動;
- sharding proxy:透明化的數據庫代理端,可以看做是一個虛擬的數據庫服務。
集成sharding jdbc
僅是集成sharding jdbc還是很簡單的,爲了更好的理解,這裏以訂單表爲例。
1. 引入依賴
<properties>
<sharding-sphere.version>4.1.0</sharding-sphere.version>
</properties>
<!-- 分庫分表:https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-spring-boot-starter -->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>${sharding-sphere.version}</version>
</dependency>
2. 配置分表規則
spring:
shardingsphere:
datasource:
names: sharding-order-system
sharding-order-system:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/order_system?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useTimezone=true
username: root
password: root
props:
# 日誌顯示SQL
sql.show: true
sharding:
tables:
# 訂單表 分表:20
order:
# 真實表 order_0
actualDataNodes: sharding-order-system.order_$->{0..19}
# 分庫策略
databaseStrategy:
none:
# 分表策略
tableStrategy:
inline:
shardingColumn: order_key
# 分片算法行表達式,需符合groovy語法 '& Integer.MAX_VALUE' 位運算使hash值爲正數
algorithmExpression: order_$->{(order_key.hashCode() & Integer.MAX_VALUE) % 20}
問題
上面雖然完成了對訂單表(order)的分表,但是sharding jdbc對一些語法不支持,官方的文檔裏說的比較籠統,如下圖:
像insert into ... select
這些語法是不支持的,而且對於沒有涉及到分表的語句,也有同樣的限制。例如,項目裏有個SQL:insert into user_temp select * from user;
在集成了sharding jdbc後,即使user表沒有配置分表,執行該SQL也會報錯。
官方的問答中提到,使用多數據源分別處理分片和不分片的情況,對分表的SQL使用sharding jdbc數據源,對不涉及到分表的SQL,使用普通數據源。
集成多數據源
我們項目中使用到了baomidou團隊開源的mybatis-plus,其團隊還開源了一個多數據源的組件:dynamic-datasource-spring-boot-starter,集成後,使用@DS
註解就可以切換數據源,非常方便。
1. 引入依賴
<!-- https://mvnrepository.com/artifact/com.baomidou/dynamic-datasource-spring-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
2. 多數據源配置
核心思路是將sharding jdbc數據源,加入到多數據源中。
/**
* 動態數據源配置:
*
* 使用{@link com.baomidou.dynamic.datasource.annotation.DS}註解,切換數據源
*
* <code>@DS(DataSourceConfiguration.SHARDING_DATA_SOURCE_NAME)</code>
*
* @author songyinyin
* @date 2020/7/27 15:19
*/
@Configuration
@AutoConfigureBefore({DynamicDataSourceAutoConfiguration.class,
SpringBootConfiguration.class})
public class DataSourceConfiguration {
/**
* 分表數據源名稱
*/
private static final String SHARDING_DATA_SOURCE_NAME = "gits_sharding";
/**
* 動態數據源配置項
*/
@Autowired
private DynamicDataSourceProperties properties;
/**
* shardingjdbc有四種數據源,需要根據業務注入不同的數據源
*
* <p>1. 未使用分片, 脫敏的名稱(默認): shardingDataSource;
* <p>2. 主從數據源: masterSlaveDataSource;
* <p>3. 脫敏數據源:encryptDataSource;
* <p>4. 影子數據源:shadowDataSource
*
*/
@Lazy
@Resource(name = "shardingDataSource")
AbstractDataSourceAdapter shardingDataSource;
@Bean
public DynamicDataSourceProvider dynamicDataSourceProvider() {
Map<String, DataSourceProperty> datasourceMap = properties.getDatasource();
return new AbstractDataSourceProvider() {
@Override
public Map<String, DataSource> loadDataSources() {
Map<String, DataSource> dataSourceMap = createDataSourceMap(datasourceMap);
// 將 shardingjdbc 管理的數據源也交給動態數據源管理
dataSourceMap.put(SHARDING_DATA_SOURCE_NAME, shardingDataSource);
return dataSourceMap;
}
};
}
/**
* 將動態數據源設置爲首選的
* 當spring存在多個數據源時, 自動注入的是首選的對象
* 設置爲主要的數據源之後,就可以支持shardingjdbc原生的配置方式了
*
* @return
*/
@Primary
@Bean
public DataSource dataSource(DynamicDataSourceProvider dynamicDataSourceProvider) {
DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
dataSource.setPrimary(properties.getPrimary());
dataSource.setStrict(properties.getStrict());
dataSource.setStrategy(properties.getStrategy());
dataSource.setProvider(dynamicDataSourceProvider);
dataSource.setP6spy(properties.getP6spy());
dataSource.setSeata(properties.getSeata());
return dataSource;
}
}
sharding jdbc有四種數據源:
- 未使用分片, 脫敏的名稱(默認): shardingDataSource;
- 主從數據源: masterSlaveDataSource;
- 脫敏數據源:encryptDataSource;
- 影子數據源:shadowDataSource
需要需要根據不同的場景,注入不同的數據源,本文以分表舉例,所以將shardingDataSource放到了多數據源(dataSourceMap)中。
3. 增加多數據源配置
在第2步,我們指定了shardingsphere數據源的名稱爲:gits_sharding
spring:
datasource:
# 動態數據源配置
dynamic:
datasource:
master:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/gits?useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true
username: root
password: root
# 指定默認數據源名稱
primary: master
# 分表配置
shardingsphere:
datasource:
names: sharding-order-system
sharding-order-system:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://172.20.20.19:3306/order_system?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useTimezone=true
username: root
password: root
props:
# 日誌顯示SQL
sql.show: true
sharding:
tables:
# 訂單表 分表:20
order:
# 真實表 order_0
actualDataNodes: sharding-order-system.order_$->{0..19}
# 分庫策略
databaseStrategy:
none:
# 分表策略
tableStrategy:
inline:
shardingColumn: order_key
# 分片算法行表達式,需符合groovy語法 '& Integer.MAX_VALUE' 位運算使hash值爲正數
algorithmExpression: order_$->{(order_key.hashCode() & Integer.MAX_VALUE) % 20}
這裏將默認數據源指定爲了普通數據源。
4. 使用
在需要分表的service方法上加上@DS("gits_sharding")
,即可切換爲sharding jdbc數據源。
@Service
@Slf4j
public class OrderServiceImpl extends OrderService {
@Override
@DS("gits_sharding")
public List<Order> getOrderByUser(OrderQueryDTO dto) throws Exception {
// 省略若干業務代碼
...
}
}
總結
sharding jdbc雖然是Apache的頂級項目,但也不是對有所SQL兼容,使用多數據源 + sharding jdbc則能跳過很多sharding jdbc的不足。