shardingsphere-JDBC功能演示
- 分库分表
- 读写分离
- 加密功能
准备工作
- 执行example模块下的manual_schema.sql,初始化数据库结构
- 修改sharding-raw-jdbc-example模块下META-INF文件夹下的配置文件,把数据库配置修改为本地配置
- 选择其中一个启动类启动-ShardingRawYamlConfigurationExample
启动类
不同启动类加载datesource信息的方式不同
yaml vs java
- yaml模式-从yaml文件中读取config配置
- java模式-在java类中配置config
rang vs 非rang
启动类中,使用模板模式调用ExampleService接口
public static void run(final ExampleService exampleService) throws SQLException {
try {
exampleService.initEnvironment();//初始化
exampleService.processSuccess();//处理过程
} finally {
exampleService.cleanEnvironment();//删除所有记录
}
}
分库分表
分表
分表规则
分库
分库规则
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两个库
- t_order和t_order_item两张表都是按照
ds_${user_id % 2}
规则--用user_id对2取模的值进行数据库路由,将数据分配到不同的数据库中
image.png
image.png
可以看到,user_id为基数的数据分到了ds_1库,偶数分到了ds_0库,实现了分库