shard-jdbc分庫(kù)分表的使用

在使用shard-jdbc遇到問(wèn)題,4.x版本和5.x版本相差很大,配置基本上不能復(fù)用。

  • 在使用4.x的時(shí)候,maven倉(cāng)庫(kù)中的最新版本是4.1.1,使用的依賴:
<!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-spring-boot-starter -->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.1.1</version>
</dependency>

application.yml配置基本如下:

# 配置分庫(kù)分表
spring:
  main:
    # 允許定義相同的bean對(duì)象去覆蓋原有的
    allow-bean-definition-overriding: true
  shardingsphere:
    props:
      sql:
        # 打開sql輸出日志
        show: true
    datasource:
      names: ds1
      ds1:
        # type: com.zaxxer.hikari.HikariDataSource
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/test?useUnicode=true&serverTimezone=UTC
        username: root
        password: 123456

    sharding:
      # 未配置分片規(guī)則的表將通過(guò)默認(rèn)數(shù)據(jù)源定位
      default-data-source-name: ds1
      tables:
        t_user:
          actual-data-nodes: ds1.t_user_$->{0..1}
          table-strategy:
            standard:
              sharding-column: user_name
              precise-algorithm-class-name: com.test.core.infrastructure.shard.HashShardingAlgorithm
      binding-tables:
        - t_user
      default-database-strategy:
        inline:
          sharding-column: id
          algorithm-expression: ds$->{1}

使用自定義的分片算法:

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * @Description 非自增字段通過(guò)hash分片
 * @Author jack
 * @Date 2024/9/3 14:25
 */
public class HashShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        // 計(jì)算用戶名的哈希值,并根據(jù)哈希值選擇分片
        String columnValue = shardingValue.getValue();
        int hashCode = columnValue.hashCode();
        int index = Math.abs(hashCode) % availableTargetNames.size();

        // 返回實(shí)際的目標(biāo)表名
        return availableTargetNames.stream().skip(index).findFirst().orElse(null);
    }
}
  • 在使用5.x的時(shí)候,maven倉(cāng)庫(kù)中的最新版本是5.2.1,使用的依賴:
<!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/shardingsphere-jdbc-core-spring-boot-starter -->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
    <version>5.2.0</version>
</dependency>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容