shardingsphere 使用

1.SS官网:

http://shardingsphere.apache.org/index_zh.html

 

2.demo-java 版本:
 


      // 配置第一个数据源
      BasicDataSource dataSource1 = new BasicDataSource();
      dataSource1.setDriverClassName("com.mysql.jdbc.Driver");
      dataSource1.setUrl("jdbc:mysql://localhost:3306/orders_0");
      dataSource1.setUsername("root");
      dataSource1.setPassword("root");
      dataSourceMap.put("orders_0", dataSource1);


      // 配置第二个数据源
      BasicDataSource dataSource2 = new BasicDataSource();
      dataSource2.setDriverClassName("com.mysql.jdbc.Driver");
      dataSource2.setUrl("jdbc:mysql://localhost:3306/orders_1");
      dataSource2.setUsername("root");
      dataSource2.setPassword("root");
      dataSourceMap.put("orders_1", dataSource2);
      /****************分片表组装************/
      // 配置分片规则 我们已经设置了相关的逻辑关系 表的关系都弄好了
      ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
      shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration());
      shardingRuleConfig.getTableRuleConfigs().add(getOrderItemTableRuleConfiguration());
      shardingRuleConfig.getBindingTableGroups().add("t_order, t_order_item");
      /****************分片具体规则************/
      //datanode为数据分片最小单元
      // 配置分库策略
      //我们采用数据库的分片是用user_id user_id %2 主要定位数据库库
      shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("user_id", "orders_${user_id % 2}"));
      //sharding-cloumn 分片字段
      // 配置分表策略 对表分片是采用我们order_id
      shardingRuleConfig.setDefaultTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("order_id", new PreciseShardingAlgorithm() {

         @Override
         public String doSharding(Collection collection, final PreciseShardingValue preciseShardingValue) {
            for (String each : collection) {
               if (each.endsWith(preciseShardingValue.getValue() % 2 + "")) {
                  return each;
               }
            }
            throw new UnsupportedOperationException();
         }
      }));
      // 获取数据源对象
      Properties properties = new Properties();
      properties.setProperty("sql.show", "true");
      DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new ConcurrentHashMap(), properties);
      JavaSytleTest2 test = new JavaSytleTest2();
      /*test.drop(dataSource);
      test.create(dataSource);
      test.insertData(dataSource);*/
      test.select(dataSource, 291325439555665920L);

 

 

3.源码分析:

sql 初始化
io.shardingsphere.api.config.TableRuleConfiguration
io.shardingsphere.core.rule.ShardingRule
io.shardingsphere.core.event.ShardingEventListenerRegistrySPILoader
io.shardingsphere.core.bootstrap.ShardingBootstrap
io.shardingsphere.shardingjdbc.jdbc.adapter.AbstractDataSourceAdapter
io.shardingsphere.shardingjdbc.api.ShardingDataSourceFact

 

你可能感兴趣的:(【Spring家族】)