shardingsphere-JDBC功能演示
- 分庫分表
- 讀寫分離
- 加密功能
準(zhǔn)備工作
- 執(zhí)行example模塊下的manual_schema.sql,初始化數(shù)據(jù)庫結(jié)構(gòu)
- 修改sharding-raw-jdbc-example模塊下META-INF文件夾下的配置文件,把數(shù)據(jù)庫配置修改為本地配置
- 選擇其中一個(gè)啟動(dòng)類啟動(dòng)-ShardingRawYamlConfigurationExample
啟動(dòng)類
不同啟動(dòng)類加載datesource信息的方式不同
yaml vs java
- yaml模式-從yaml文件中讀取config配置
- java模式-在java類中配置config
rang vs 非rang
啟動(dòng)類中,使用模板模式調(diào)用ExampleService接口
public static void run(final ExampleService exampleService) throws SQLException {
try {
exampleService.initEnvironment();//初始化
exampleService.processSuccess();//處理過程
} finally {
exampleService.cleanEnvironment();//刪除所有記錄
}
}
分庫分表
分表
分表規(guī)則
分庫
分庫規(guī)則
rules:
- !SHARDING
tables:
t_order:
actualDataNodes: ds_${0..1}.t_order
keyGenerateStrategy:
column: order_id
keyGeneratorName: snowflake
t_order_item:
actualDataNodes: ds_${0..1}.t_order_item
keyGenerateStrategy:
column: order_item_id
keyGeneratorName: snowflake
bindingTables:
- t_order,t_order_item
broadcastTables:
- t_address
defaultDatabaseStrategy:
standard:
shardingColumn: user_id
shardingAlgorithmName: database_inline
defaultTableStrategy:
none:
shardingAlgorithms:
database_inline:
type: INLINE
props:
algorithm-expression: ds_${user_id % 2}
keyGenerators:
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
- 有ds_0和ds_1兩個(gè)庫
- t_order和t_order_item兩張表都是按照
ds_${user_id % 2}規(guī)則--用user_id對2取模的值進(jìn)行數(shù)據(jù)庫路由,將數(shù)據(jù)分配到不同的數(shù)據(jù)庫中

image.png

image.png
可以看到,user_id為基數(shù)的數(shù)據(jù)分到了ds_1庫,偶數(shù)分到了ds_0庫,實(shí)現(xiàn)了分庫