当前位置: 代码网 > it编程>编程语言>Java > SpringBoot集成ShardingSphere实现数据库分表

SpringBoot集成ShardingSphere实现数据库分表

2024年12月19日 • Java •我要评论
shardingsphere功能介绍shardingsphere 是一个开源的分布式数据库中间件,旨在为应用提供数据库分片、读写分离、分布式事务等功能。它能够与现有的数据库无缝集成,并且支持多种数据库

shardingsphere功能介绍

shardingsphere 是一个开源的分布式数据库中间件,旨在为应用提供数据库分片、读写分离、分布式事务等功能。它能够与现有的数据库无缝集成,并且支持多种数据库(包括 mysql、sql server、oracle 等),且无需对应用代码做太多改动。

官网:shardingsphere.apache.org/

shardingsphere 提供以下核心功能

1.分库分表 (sharding):

  • 通过配置规则将数据划分到多个数据库或表中,常见的分片方式包括基于范围、哈希、复合字段等。
  • 支持多种分片策略,如按某个字段值分片(例如,基于 user_id 或 order_id 等字段),以及表和数据库的分片。

2.读写分离 (read/write splitting):

可以通过配置实现读操作与写操作分离。一般情况下,写操作指向主库,读操作可以从多个副本库进行负载均衡读取。

3.数据脱敏与加密 (data masking & encryption):

提供数据加密与脱敏功能,保护数据库中的敏感数据。

4.分布式事务 (distributed transaction):

支持分布式事务,确保跨多个数据库操作时的一致性。

5.透明性与兼容性:

shardingsphere 是一个数据库中间件,能够透明地将分片策略应用到应用层。它支持与 spring boot、spring cloud、mybatis、jpa 等框架的集成,应用层代码无需做额外改动。

6.支持多种数据库:

shardingsphere 支持 mysql、postgresql、sql server、oracle 等常见数据库。可以灵活地选择需要支持的数据库。

7.高可扩展性:

shardingsphere 提供了扩展点,支持灵活的功能扩展与二次开发。

spring boot中使用shardingsphere实现分表

spring boot中使用shardingsphere实现分表,并同时支持sql server、mysql、oracle、postgresql

在 spring boot 中使用 shardingsphere 实现分表,并同时支持 sql server、mysql、oracle 和 postgresql 数据库,需要进行以下步骤。通过配置 shardingsphere 的分片策略,结合不同数据库的连接设置,可以实现跨多个数据库的数据分片。

步骤 1: 引入必要的依赖

在 pom.xml 文件中,添加 spring boot、shardingsphere 和不同数据库的 jdbc 驱动。

<dependencies>
    <!-- spring boot 基础依赖 -->
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-data-jpa</artifactid>
    </dependency>

    <!-- shardingsphere-jdbc for spring boot -->
    <dependency>
        <groupid>org.apache.shardingsphere</groupid>
        <artifactid>sharding-jdbc-spring-boot-starter</artifactid>
        <version>5.0.0</version> <!-- 请根据需要选择合适的版本 -->
    </dependency>

    <!-- mysql 驱动 -->
    <dependency>
        <groupid>mysql</groupid>
        <artifactid>mysql-connector-java</artifactid>
    </dependency>

    <!-- sql server 驱动 -->
    <dependency>
        <groupid>com.microsoft.sqlserver</groupid>
        <artifactid>mssql-jdbc</artifactid>
        <version>9.4.1.jre8</version>
    </dependency>

    <!-- oracle 驱动 -->
    <dependency>
        <groupid>com.oracle.database.jdbc</groupid>
        <artifactid>ojdbc8</artifactid>
        <version>19.8.0.0</version>
    </dependency>

    <!-- postgresql 驱动 -->
    <dependency>
        <groupid>org.postgresql</groupid>
        <artifactid>postgresql</artifactid>
        <version>42.5.0</version>
    </dependency>
</dependencies>

步骤 2: 配置 application.yml

在 application.yml 中,配置 shardingsphere 相关数据源以及分片策略。

spring:
  datasource:
    # 配置 mysql 数据源
    mysql:
      url: jdbc:mysql://localhost:3306/mysql_db
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.driver

    # 配置 sql server 数据源
    sqlserver:
      url: jdbc:sqlserver://localhost:1433;databasename=sqlserver_db
      username: sa
      password: password
      driver-class-name: com.microsoft.sqlserver.jdbc.sqlserverdriver

    # 配置 oracle 数据源
    oracle:
      url: jdbc:oracle:thin:@localhost:1521:orcl
      username: oracle
      password: oracle
      driver-class-name: oracle.jdbc.oracledriver

    # 配置 postgresql 数据源
    postgresql:
      url: jdbc:postgresql://localhost:5432/postgresql_db
      username: postgres
      password: password
      driver-class-name: org.postgresql.driver

  sharding:
    jdbc:
      config:
        data-source:
          mysql:
            url: jdbc:mysql://localhost:3306/mysql_db
            username: root
            password: root
            driver-class-name: com.mysql.cj.jdbc.driver
          sqlserver:
            url: jdbc:sqlserver://localhost:1433;databasename=sqlserver_db
            username: sa
            password: password
            driver-class-name: com.microsoft.sqlserver.jdbc.sqlserverdriver
          oracle:
            url: jdbc:oracle:thin:@localhost:1521:orcl
            username: oracle
            password: oracle
            driver-class-name: oracle.jdbc.oracledriver
          postgresql:
            url: jdbc:postgresql://localhost:5432/postgresql_db
            username: postgres
            password: password
            driver-class-name: org.postgresql.driver

      rules:
        sharding:
          tables:
            order:
              actual-data-nodes: mysql.order_${0..1},sqlserver.order_${0..1},oracle.order_${0..1},postgresql.order_${0..1}
              table-strategy:
                inline:
                  sharding-column: order_id
                  algorithm-expression: order_${order_id % 2}
            user:
              actual-data-nodes: mysql.user_${0..1},sqlserver.user_${0..1},oracle.user_${0..1},postgresql.user_${0..1}
              table-strategy:
                inline:
                  sharding-column: user_id
                  algorithm-expression: user_${user_id % 2}

解释:

  • data-source: 定义了每个数据库的数据源,包括 mysql、sql server、oracle 和 postgresql。
  • sharding: 配置了分片规则。每个表(如 order 和 user)在不同数据库中都有实际的数据节点,例如 mysql.order_0, sqlserver.order_0 等。
  • table-strategy: 使用 inline 策略,依据 order_id 或 user_id 来进行分片,例如 order_id % 2 表示将数据分片为 order_0 或 order_1。

步骤 3: 配置 shardingsphere 数据源和分片规则

你需要编写 java 配置类来配置 shardingsphere 数据源和分片规则。

shardingconfig.java:

@configuration
@enabletransactionmanagement
public class shardingconfig {

    @bean
    public datasource datasource() throws sqlexception {
        return shardingdatasourcefactory.createdatasource(createdatasourcemap(), createshardingruleconfig());
    }

    private map<string, datasource> createdatasourcemap() {
        map<string, datasource> datasourcemap = new hashmap<>();
        datasourcemap.put("mysql", createdatasource("mysql"));
        datasourcemap.put("sqlserver", createdatasource("sqlserver"));
        datasourcemap.put("oracle", createdatasource("oracle"));
        datasourcemap.put("postgresql", createdatasource("postgresql"));
        return datasourcemap;
    }

    private datasource createdatasource(string datasourcename) {
        hikaridatasource datasource = new hikaridatasource();
        switch (datasourcename) {
            case "mysql":
                datasource.setjdbcurl("jdbc:mysql://localhost:3306/mysql_db");
                datasource.setusername("root");
                datasource.setpassword("root");
                datasource.setdriverclassname("com.mysql.cj.jdbc.driver");
                break;
            case "sqlserver":
                datasource.setjdbcurl("jdbc:sqlserver://localhost:1433;databasename=sqlserver_db");
                datasource.setusername("sa");
                datasource.setpassword("password");
                datasource.setdriverclassname("com.microsoft.sqlserver.jdbc.sqlserverdriver");
                break;
            case "oracle":
                datasource.setjdbcurl("jdbc:oracle:thin:@localhost:1521:orcl");
                datasource.setusername("oracle");
                datasource.setpassword("oracle");
                datasource.setdriverclassname("oracle.jdbc.oracledriver");
                break;
            case "postgresql":
                datasource.setjdbcurl("jdbc:postgresql://localhost:5432/postgresql_db");
                datasource.setusername("postgres");
                datasource.setpassword("password");
                datasource.setdriverclassname("org.postgresql.driver");
                break;
            default:
                throw new illegalargumentexception("unsupported datasource");
        }
        return datasource;
    }

    private shardingruleconfiguration createshardingruleconfig() {
        shardingruleconfiguration shardingruleconfig = new shardingruleconfiguration();

        // 配置订单表的分片规则
        shardingruleconfig.gettableruleconfigs().add(createordertablerule());
        // 配置用户表的分片规则
        shardingruleconfig.gettableruleconfigs().add(createusertablerule());

        // 设置默认数据源
        shardingruleconfig.setdefaultdatasourcename("mysql");

        return shardingruleconfig;
    }

    private tableruleconfiguration createordertablerule() {
        tableruleconfiguration ordertableruleconfig = new tableruleconfiguration();
        ordertableruleconfig.setlogictable("order");
        ordertableruleconfig.setactualdatanodes("mysql.order_${0..1},sqlserver.order_${0..1},oracle.order_${0..1},postgresql.order_${0..1}");
        ordertableruleconfig.settableshardingstrategyconfig(new inlineshardingstrategyconfiguration("order_id", "order_${order_id % 2}"));
        return ordertableruleconfig;
    }

    private tableruleconfiguration createusertablerule() {
        tableruleconfiguration usertableruleconfig = new tableruleconfiguration();
        usertableruleconfig.setlogictable("user");
        usertableruleconfig.setactualdatanodes("mysql.user_${0..1},sqlserver.user_${0..1},oracle.user_${0..1},postgresql.user_${0..1}");
        usertableruleconfig.settableshardingstrategyconfig(new inlineshardingstrategyconfiguration("user_id", "user_${user_id % 2}"));
        return usertableruleconfig;
    }
}

说明:

  • createdatasourcemap() 方法将所有数据源注册到 shardingdatasourcefactory。
  • createshardingruleconfig() 方法定义了分片规则,分别为 order 和 user 表指定了分片策略。
  • 分片策略通过 inlineshardingstrategyconfiguration 来设置,依据字段 order_id 或 user_id 进行分片。

步骤 4: 创建实体类

你需要根据业务需求定义实体类。例如:

@entity
public class order {

    @id
    private long orderid;
    private string orderdetails;

    // getters and setters
}

@entity
public class user {

    @id
    private long userid;
    private string username;

    // getters and setters
}

步骤 5: 测试

创建一些简单的测试用例,来验证 shardingsphere 的分片是否按预期工作。你可以通过执行一些简单的 crud 操作来检查分片效果。

@runwith(springrunner.class)
@springboottest
public class shardingtest {

    @autowired
    private orderrepository orderrepository;

    @test
    public void testordersharding() {
        order order = new order();
        order.setorderid(1l);
        order.setorderdetails("test order");
        orderrepository.save(order);

        optional<order> savedorder = orderrepository.findbyid(1l);
        asserttrue(savedorder.ispresent());
    }
}

总结

通过上面的配置,shardingsphere 能够实现跨多个数据库的分片,包括 mysql、sql server、oracle 和 postgresql。在实际应用中,你可以根据需要调整分片规则,结合数据源来实现分布式数据管理。

以上就是springboot集成shardingsphere实现数据库分表的详细内容,更多关于springboot shardingsphere数据库分表的资料请关注代码网其它相关文章!

赞 (0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com