(三)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中。

猜你喜欢

转载自blog.csdn.net/woshiwjma956/article/details/106659093