Sharding-Jdbc集成mybatis-plus實現分庫分表解決方案

項目地址:php

官方文檔:html

1、運行測試

  • Step 1:新建兩個數據庫分別爲seal_sharding、seal_sharding1
  • Step 2:分別導入db目錄下sql文件
  • Step 3:打開項目,配置環境變量MYSQL_HOST、MYSQL_PORT以及用戶名和密碼
  • Step 4:運行測試文件(test包下)

2、租戶ID的獲取

修改config包下MybaitsPlusConfig.java,獲取當前登陸用戶的租戶ID,這裏默認寫1
@Override
public Expression getTenantId() {
    try {
        // 獲取當前登陸用戶租戶ID
        String tenantId = "1";
        if (!StrUtil.isEmpty(tenantId)) {
            return new LongValue(tenantId);
        }
        throw new Exception(RetBack.errorJson(4001, "該租戶不存在"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new LongValue(-1L);
}

3、分庫分表策略

  • 分庫:根據表字段 租戶ID(tenant_id) 模2(奇偶數)進行分庫
  • 分表:根據表字段 id 去hascode模2(奇偶數)進行發分表,分佈式主鍵採用雪花算法(SNOWFLAKE),詳見:Sharding-JDBC

3、只分表不分庫

本項目爲兩個數據源實現分庫和分表,若是隻分表不分庫,只須要添加一個數據源便可java

4、實現注意點

  • Sharding-JDBC採用3.x版本
  • 須要複寫MybaitsPlus配置
  • 排除自動數據源加載
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class, 
DataSourceAutoConfiguration.class})

附、Mybatis-Plus多數據源

若是不使用Sharding-JDBC,而須要多數據源,能夠採用Mybaits-Plus多數據源方案,詳見官方文檔,後面我會把示例項目分享給你們,敬請期待。能夠加我互相交流。git

<center style="font-size:18px">開源不易,且用且珍惜!</center>github



<center style="font-size:16px">贊助做者,互相交流</center>

算法

<div style="display:flex;justify-content:center;align-item:center">
<img src="https://user-gold-cdn.xitu.io/2020/5/29/1725e23e1228866e?w=1080&h=1080&f=png&s=342366" style="width:180px;height:180px;padding:20px"/>sql

<img src="https://user-gold-cdn.xitu.io/2020/5/29/1725e23e121cbaa2?w=300&h=299&f=gif&s=20783" style="width:180px;height:180px;padding:20px"/>
</div>數據庫

轉載請註明:個人技術分享 » Sharding-Jdbc集成mybatis-plus實現分庫分表解決方案apache

相關文章
相關標籤/搜索