SpringBoot2.0整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表

一、水平分割

公司主營業(yè)務(wù):網(wǎng)站設(shè)計制作、成都網(wǎng)站建設(shè)、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。成都創(chuàng)新互聯(lián)公司是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊有機(jī)會用頭腦與智慧不斷的給客戶帶來驚喜。成都創(chuàng)新互聯(lián)公司推出寶應(yīng)免費(fèi)做網(wǎng)站回饋大家。

1、水平分庫
1)、概念:
 以字段為依據(jù),按照一定策略,將一個庫中的數(shù)據(jù)拆分到多個庫中。
2)、結(jié)果
 每個庫的結(jié)構(gòu)都一樣;數(shù)據(jù)都不一樣;
 所有庫的并集是全量數(shù)據(jù);
2、水平分表
1)、概念
 以字段為依據(jù),按照一定策略,將一個表中的數(shù)據(jù)拆分到多個表中。
2)、結(jié)果
 每個表的結(jié)構(gòu)都一樣;數(shù)據(jù)都不一樣;
 所有表的并集是全量數(shù)據(jù);

二、Shard-jdbc 中間件

1、架構(gòu)圖

SpringBoot 2.0 整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表

2、特點(diǎn)

1)、Sharding-JDBC直接封裝JDBC API,舊代碼遷移成本幾乎為零。
2)、適用于任何基于Java的ORM框架,如Hibernate、Mybatis等 。
3)、可基于任何第三方的數(shù)據(jù)庫連接池,如DBCP、C3P0、 BoneCP、Druid等。
4)、以jar包形式提供服務(wù),無proxy代理層,無需額外部署,無其他依賴。
5)、分片策略靈活,可支持等號、between、in等多維度分片,也可支持多分片鍵。
6)、SQL解析功能完善,支持聚合、分組、排序、limit、or等查詢。

三、項目演示

1、項目結(jié)構(gòu)

SpringBoot 2.0 整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表

springboot     2.0 版本
druid          1.1.13 版本
sharding-jdbc  3.1 版本

2、數(shù)據(jù)庫配置

SpringBoot 2.0 整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表

SpringBoot 2.0 整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表

SpringBoot 2.0 整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表

一臺基礎(chǔ)庫映射(shard_one)
兩臺庫做分庫分表(shard_two,shard_three)。
表使用:table_one,table_two

3、核心代碼塊

數(shù)據(jù)源配置文件

spring:
 datasource:
  # 數(shù)據(jù)源:shard_one
  dataOne:
   type: com.alibaba.druid.pool.DruidDataSource
   druid:
    driverClassName: com.MySQL.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shard_one?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
    username: root
    password: 123
    initial-size: 10
    max-active: 100
    min-idle: 10
    max-wait: 60000
    pool-prepared-statements: true
    max-pool-prepared-statement-per-connection-size: 20
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 300000
    max-evictable-idle-time-millis: 60000
    validation-query: SELECT 1 FROM DUAL
    # validation-query-timeout: 5000
    test-on-borrow: false
    test-on-return: false
    test-while-idle: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  # 數(shù)據(jù)源:shard_two
  dataTwo:
   type: com.alibaba.druid.pool.DruidDataSource
   druid:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shard_two?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
    username: root
    password: 123
    initial-size: 10
    max-active: 100
    min-idle: 10
    max-wait: 60000
    pool-prepared-statements: true
    max-pool-prepared-statement-per-connection-size: 20
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 300000
    max-evictable-idle-time-millis: 60000
    validation-query: SELECT 1 FROM DUAL
    # validation-query-timeout: 5000
    test-on-borrow: false
    test-on-return: false
    test-while-idle: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  # 數(shù)據(jù)源:shard_three
  dataThree:
   type: com.alibaba.druid.pool.DruidDataSource
   druid:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shard_three?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
    username: root
    password: 123
    initial-size: 10
    max-active: 100
    min-idle: 10
    max-wait: 60000
    pool-prepared-statements: true
    max-pool-prepared-statement-per-connection-size: 20
    time-between-eviction-runs-millis: 60000
    min-evictable-idle-time-millis: 300000
    max-evictable-idle-time-millis: 60000
    validation-query: SELECT 1 FROM DUAL
    # validation-query-timeout: 5000
    test-on-borrow: false
    test-on-return: false
    test-while-idle: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

數(shù)據(jù)庫分庫策略

/**
 * 數(shù)據(jù)庫映射計算
 */
public class DataSourceAlg implements PreciseShardingAlgorithm<String> {

  private static Logger LOG = LoggerFactory.getLogger(DataSourceAlg.class);
  @Override
  public String doSharding(Collection<String> names, PreciseShardingValue<String> value) {
    LOG.debug("分庫算法參數(shù) {},{}",names,value);
    int hash = HashUtil.rsHash(String.valueOf(value.getValue()));
    return "ds_" + ((hash % 2) + 2) ;
  }
}

數(shù)據(jù)表1分表策略

/**
 * 分表算法
 */
public class TableOneAlg implements PreciseShardingAlgorithm<String> {
  private static Logger LOG = LoggerFactory.getLogger(TableOneAlg.class);
  /**
   * 該表每個庫分5張表
   */
  @Override
  public String doSharding(Collection<String> names, PreciseShardingValue<String> value) {
    LOG.debug("分表算法參數(shù) {},{}",names,value);
    int hash = HashUtil.rsHash(String.valueOf(value.getValue()));
    return "table_one_" + (hash % 5+1);
  }
}

數(shù)據(jù)表2分表策略

/**
 * 分表算法
 */
public class TableTwoAlg implements PreciseShardingAlgorithm<String> {
  private static Logger LOG = LoggerFactory.getLogger(TableTwoAlg.class);
  /**
   * 該表每個庫分5張表
   */
  @Override
  public String doSharding(Collection<String> names, PreciseShardingValue<String> value) {
    LOG.debug("分表算法參數(shù) {},{}",names,value);
    int hash = HashUtil.rsHash(String.valueOf(value.getValue()));
    return "table_two_" + (hash % 5+1);
  }
}

數(shù)據(jù)源集成配置

/**
 * 數(shù)據(jù)庫分庫分表配置
 */
@Configuration
public class ShardJdbcConfig {
  // 省略了 druid 配置,源碼中有
  /**
   * Shard-JDBC 分庫配置
   */
  @Bean
  public DataSource dataSource (@Autowired DruidDataSource dataOneSource,
                 @Autowired DruidDataSource dataTwoSource,
                 @Autowired DruidDataSource dataThreeSource) throws Exception {
    ShardingRuleConfiguration shardJdbcConfig = new ShardingRuleConfiguration();
    shardJdbcConfig.getTableRuleConfigs().add(getTableRule01());
    shardJdbcConfig.getTableRuleConfigs().add(getTableRule02());
    shardJdbcConfig.setDefaultDataSourceName("ds_0");
    Map<String,DataSource> dataMap = new LinkedHashMap<>() ;
    dataMap.put("ds_0",dataOneSource) ;
    dataMap.put("ds_2",dataTwoSource) ;
    dataMap.put("ds_3",dataThreeSource) ;
    Properties prop = new Properties();
    return ShardingDataSourceFactory.createDataSource(dataMap, shardJdbcConfig, new HashMap<>(), prop);
  }

  /**
   * Shard-JDBC 分表配置
   */
  private static TableRuleConfiguration getTableRule01() {
    TableRuleConfiguration result = new TableRuleConfiguration();
    result.setLogicTable("table_one");
    result.setActualDataNodes("ds_${2..3}.table_one_${1..5}");
    result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new DataSourceAlg()));
    result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new TableOneAlg()));
    return result;
  }
  private static TableRuleConfiguration getTableRule02() {
    TableRuleConfiguration result = new TableRuleConfiguration();
    result.setLogicTable("table_two");
    result.setActualDataNodes("ds_${2..3}.table_two_${1..5}");
    result.setDatabaseShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new DataSourceAlg()));
    result.setTableShardingStrategyConfig(new StandardShardingStrategyConfiguration("phone", new TableTwoAlg()));
    return result;
  }
}

測試代碼執(zhí)行流程

@RestController
public class ShardController {
  @Resource
  private ShardService shardService ;
  /**
   * 1、建表流程
   */
  @RequestMapping("/createTable")
  public String createTable (){
    shardService.createTable();
    return "success" ;
  }
  /**
   * 2、生成表 table_one 數(shù)據(jù)
   */
  @RequestMapping("/insertOne")
  public String insertOne (){
    shardService.insertOne();
    return "SUCCESS" ;
  }
  /**
   * 3、生成表 table_two 數(shù)據(jù)
   */
  @RequestMapping("/insertTwo")
  public String insertTwo (){
    shardService.insertTwo();
    return "SUCCESS" ;
  }
  /**
   * 4、查詢表 table_one 數(shù)據(jù)
   */
  @RequestMapping("/selectOneByPhone/{phone}")
  public TableOne selectOneByPhone (@PathVariable("phone") String phone){
    return shardService.selectOneByPhone(phone);
  }
  /**
   * 5、查詢表 table_one 數(shù)據(jù)
   */
  @RequestMapping("/selectTwoByPhone/{phone}")
  public TableTwo selectTwoByPhone (@PathVariable("phone") String phone){
    return shardService.selectTwoByPhone(phone);
  }
}

四、項目源碼

GitHub:知了一笑

https://github.com/cicadasmile/middle-ware-parent

總結(jié)

以上所述是小編給大家介紹的SpringBoot 2.0 整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對創(chuàng)新互聯(lián)網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!

本文標(biāo)題:SpringBoot2.0整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表
新聞來源:http://www.muchs.cn/article42/ghgehc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)標(biāo)簽優(yōu)化、定制網(wǎng)站、外貿(mào)建站虛擬主機(jī)、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司