shardingsphere-JDBC功能演示

shardingsphere-JDBC功能演示

  1. 分库分表
  2. 读写分离
  3. 加密功能

准备工作

  1. 执行example模块下的manual_schema.sql,初始化数据库结构
  2. 修改sharding-raw-jdbc-example模块下META-INF文件夹下的配置文件,把数据库配置修改为本地配置
  3. 选择其中一个启动类启动-ShardingRawYamlConfigurationExample

启动类

不同启动类加载datesource信息的方式不同

yaml vs java

  1. yaml模式-从yaml文件中读取config配置
  2. 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
  1. 有ds_0和ds_1两个库
  2. t_order和t_order_item两张表都是按照ds_${user_id % 2}规则--用user_id对2取模的值进行数据库路由,将数据分配到不同的数据库中
image.png
image.png

可以看到,user_id为基数的数据分到了ds_1库,偶数分到了ds_0库,实现了分库

读写分离

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容