(三)ShardingSphere入门垂直切分

  • 垂直切分:按照不同的表(或者Schema)切分到不同的数据库(主机)上。一个数据库由很多表构成,每张表对应不同的业务,垂直切分是按照业务将表进行分类,分布到不同数据库上。简单的说就是原来数据库中有很多表,将一些表单独出来放在另外一个新的数据库中,或者将一个表中某一些字段列抽离出来成为一个新的表。

    垂直切分将Student表拆分到ss1数据库中的student表中,将Teacher表拆分到ss2的teacher表中,可以实现专表专库。配置yml类似如下

#  多库垂直切分
spring:
  shardingsphere:
    # 所有数据库的别名
    datasource:
      names: ss1,ss2
      # 具体数据库的配置信息
      ss1:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/ss1?serverTimezone=Asia/Shanghai
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: admin
      ss2:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/ss2?serverTimezone=Asia/Shanghai
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: admin
    # 分表分库策略
    sharding:
      # 需要分表的策略
      tables:
        # 学生表只存在ss1数据库中的student表中
        student:
          actual-data-nodes: ss1.student
          # 主键生成规则 默认使用雪花算法
          key-generator:
            column: id
            type: SNOWFLAKE
          # 分表策略
          table-strategy:
            inline:
              algorithm-expression: student
              sharding-column: id
        # 教师表只存在ss2数据库中的student表中
        teacher:
          actual-data-nodes: ss2.teacher
          # 主键生成规则 默认使用雪花算法
          key-generator:
            column: id
            type: SNOWFLAKE
          # 分表策略
          table-strategy:
            inline:
              algorithm-expression: teacher
              sharding-column: id

    props:
      # 实际生成SQL
      sql:
        show: true
  main:
    allow-bean-definition-overriding: true
@Data
public class Student {
    private Long id;
    private String name;
}

@Data
public class Teacher {
    private Long id;
    private String name;
}
@RunWith(SpringRunner.class)
@ActiveProfiles("multipleDatasourceVertical")
@SpringBootTest
public class MultipleDataSourceVerticalTest {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Test
    public void testInsert(){
        Student student = new Student();
        student.setName("student1");
        studentMapper.insert(student);

        Teacher teacher = new Teacher();
        teacher.setName("teacher1");
        teacherMapper.insert(teacher);

    }

    @Test
    public void testSelect(){
        System.out.println(studentMapper.selectList(null));
        System.out.println(teacherMapper.selectList(null));
    }

}

调用测试代码发现垂直分库成功,学生只会插入到ss1.student中,老师只会插入ss2.teacher中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值