shardingJdbc5实现分库分表,多租户

实现案例springboot+mybatis-plus+shardingJdbc5

1.准备工作,springboot+mybatis-plus工程,创建两个数据库,各包含t_pro_area,t_pro_fram两张表,字段随意

2.引入shardingjdbc  jar

<!-- 分库分表  -->
<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
    <version>5.1.2</version>
</dependency>

3.yml文件配置

spring:
  shardingsphere:
    props:
      # 日志显示具体的SQL
      sql-show: false
    # 是否开启
    datasource:
      # 数据源(逻辑名字)
      names: ds0,ds1
      # 配置数据源
      ds0:
        type: com.zaxxer.hikari.HikariDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        jdbcUrl: jdbc:mysql://localhost:3306/fishery-1?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimeZone=GMT%2B8&allowPublicKeyRetrieval=true
        username: root
        password: 123456
      ds1:
        type: com.zaxxer.hikari.HikariDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        jdbcUrl: jdbc:mysql://localhost:3306/fishery-2?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimeZone=GMT%2B8&allowPublicKeyRetrieval=true
        username: root
        password: 123456

    # 分片的配置
    rules:
      sharding:
        # 表的分片策略
        tables:
          # 逻辑表的名称
          t_pro_fram:
            # 数据节点配置,采用Groovy表达式
            actual-data-nodes: ds$->{0..1}.t_pro_fram
            # 配置策略
            database-strategy: #分库策略
              standard:
                sharding-column: sort   # 分片列名称
                sharding-algorithm-name: user_inline # 分片算法名称

#            table-strategy: #分表策略
#              standard:
#                sharding-column: sort
#                sharding-algorithm-name: database_alg
        
        #分片算法名
        sharding-algorithms:
          user_inline:
            type: inline
            props:
              algorithm-expression: ds$->{sort % 2}

测试controller

@RestController
@RequestMapping("test")
public class tController {  

    @Autowired
    private ProFarmService proFarmService;

    @GetMapping("/list")
    public String list() {


        for (int i = 1 ; i < 10; i++) {
            ProFarm test =new ProFarm();
            test.setCusNo("嗡嗡嗡"+i);
            test.setSort(i);
            proFarmService.save(test);
        }
        retun "seccess";
    }
}

规则ds$->{so

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值