1 Star 2 Fork 1

silianpan / seal-sharding

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

Sharding-Jdbc集成mybatis-plus实现分库分表解决方案

项目地址:

官方文档:

一、运行测试

  • Step 1:新建两个数据库分别为seal_sharding、seal_sharding1
  • Step 2:分别导入db目录下sql文件
  • Step 3:打开项目,配置环境变量MYSQL_HOST、MYSQL_PORT以及用户名和密码
  • Step 4:运行测试文件(test包下)

二、租户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);
}

三、分库分表策略

  • 分库:根据表字段 租户ID(tenant_id) 模2(奇偶数)进行分库
  • 分表:根据表字段 id 去hascode模2(奇偶数)进行发分表,分布式主键采用雪花算法(SNOWFLAKE),详见:Sharding-JDBC

三、只分表不分库

本项目为两个数据源实现分库和分表,如果只分表不分库,只需要添加一个数据源即可

四、实现注意点

  • Sharding-JDBC采用3.x版本
  • 需要复写MybaitsPlus配置
  • 排除自动数据源加载
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class, 
DataSourceAutoConfiguration.class})

附、Mybatis-Plus多数据源

如果不使用Sharding-JDBC,而需要多数据源,可以采用Mybaits-Plus多数据源方案,详见官方文档,后面我会把示例项目分享给大家,敬请期待。可以加我互相交流。

开源不易,且用且珍惜!


赞助作者,互相交流
MIT License Copyright (c) 2020 silianpan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

Demo project for Sharding-JDBC and Mybaits-Plus 展开 收起
Java
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/twofloor/seal-sharding.git
git@gitee.com:twofloor/seal-sharding.git
twofloor
seal-sharding
seal-sharding
master

搜索帮助