ShardingSphere实现分库分表

x33g5p2x  于2022-03-15 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(178)

一、简介

Apache ShardingSphere 是一套开源的分布式数据库解决方案组成的生态圈,它由 JDBC、Proxy 和 Sidecar(规划中)这 3 款既能够独立部署,又支持混合部署配合使用的产品组成。 它们均提供标准化的数据水平扩展、分布式事务和分布式治理等功能,可适用于如 Java 同构、异构语言、云原生等各种多样化的应用场景。

Apache ShardingSphere 旨在充分合理地在分布式的场景下利用关系型数据库的计算和存储能力,而并非实现一个全新的关系型数据库。 关系型数据库当今依然占有巨大市场份额,是企业核心系统的基石,未来也难于撼动,我们更加注重在原有基础上提供增量,而非颠覆。

Apache ShardingSphere 5.x 版本开始致力于可插拔架构,项目的功能组件能够灵活的以可插拔的方式进行扩展。 目前,数据分片、读写分离、数据加密、影子库压测等功能,以及 MySQL、PostgreSQL、SQLServer、Oracle 等 SQL 与协议的支持,均通过插件的方式织入项目。 开发者能够像使用积木一样定制属于自己的独特系统。Apache ShardingSphere 目前已提供数十个 SPI 作为系统的扩展点,仍在不断增加中。

ShardingSphere 已于2020年4月16日成为 Apache 软件基金会的顶级项目。

二、项目使用

1、引入依赖

<dependency>
   <groupId>org.apache.shardingsphere</groupId>
    <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
    <version>4.0.0-RC2</version>
</dependency>

2、数据库

3、实体类

@Data
public class User {
    private Integer id;
    private String name;
    private Integer age;
}

4、mapper

这里用的Mybatis-plus 3.4版本。

@Mapper
public interface UserMapper extends BaseMapper<User> {

}

5、yml配置

spring:
  shardingsphere:
    datasource:
      #数据库分库名
      names: ds0,ds1
      ds0:
        #type为数据源,如果是Druid数据库连接池,可以去改
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306/test0?characterEncoding=utf-8&serverTimezone=UTC
        username: root
        password: root
      ds1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306/test1?characterEncoding=utf-8&serverTimezone=UTC
        username: root
        password: root
    # 分片规则
    sharding:
      default-database-strategy:
        inline:
          algorithm-expression: ds$->{id%2}
          sharding-column: id
      tables:
        user:
          actual-data-nodes: ds${0..1}.user_${0..2}
          table-strategy:
            inline:
              algorithm-expression: user_${age%2}
              sharding-column: age
    # 在日志中SQL语句
    props:
      sql:
        show: true

6、测试类

@SpringBootTest
class DemoApplicationTests {
    @Resource
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        User user = new User();
        user.setId(1);
        user.setName("666");
        user.setAge(16);
        userMapper.insert(user);
    }

	@Test
    void contextLoads2() {
        User user = new User();
        user.setId(2);
        user.setName("666");
        user.setAge(17);
        userMapper.insert(user);
    }
}

7、数据

相关文章