若依ruoyicloud下自定义分表shardingsphere-jdbc-core-spring-boot-starter[实战配置]

ShardingSphere-JDBC-Core-Spring-Boot-Starter 和 ShardingSphere-JDBC 是两个不同但又相关的项目,它们的主要区别如下:
概念与定位
ShardingSphere-JDBC:是 ShardingSphere 项目中的一个重要模块,它是一个轻量级的 Java 框架,主要功能是为了实现数据库的分库分表、读写分离等操作,它可以在 Java 应用中像使用普通 JDBC 驱动一样使用,对应用程序的侵入性较小。
ShardingSphere-JDBC-Core-Spring-Boot-Starter:是基于 Spring Boot 的启动器(Starter),它的作用是简化 ShardingSphere-JDBC 在 Spring Boot 项目中的集成和配置。它将 ShardingSphere-JDBC 与 Spring Boot 的自动配置机制相结合,使得开发者可以更方便地在 Spring Boot 环境中使用 ShardingSphere-JDBC 的功能。
功能特性
ShardingSphere-JDBC:提供了全面的数据库分片和读写分离功能。它支持多种分片策略,包括按照哈希值、范围、列表等方式进行分片,能够根据业务需求灵活地将数据分散到多个数据库或表中。同时,它也支持动态数据源切换,方便实现读写分离,提高系统的性能和可用性。
ShardingSphere-JDBC-Core-Spring-Boot-Starter:主要特性在于其与 Spring Boot 的深度集成。它通过自动配置功能,减少了在 Spring Boot 项目中配置 ShardingSphere-JDBC 的繁琐步骤。开发者只需在项目的配置文件中进行简单的配置,就可以快速启用 ShardingSphere-JDBC 的功能。
使用场景
ShardingSphere-JDBC:适用于各种 Java 项目,无论是传统的 Java Web 应用,还是基于微服务架构的分布式系统,只要需要对数据库进行分库分表或读写分离操作,都可以使用 ShardingSphere-JDBC。
ShardingSphere-JDBC-Core-Spring-Boot-Starter:主要适用于使用 Spring Boot 框架构建的项目。如果项目已经基于 Spring Boot 开发,并且需要使用 ShardingSphere-JDBC 来实现数据库的相关功能,那么使用 ShardingSphere-JDBC-Core-Spring-Boot-Starter 可以大大简化集成过程,提高开发效率。
依赖关系与配置
ShardingSphere-JDBC:在使用时,需要在项目中引入相应的依赖坐标。配置方面,需要手动创建数据源、配置分片规则等,相对来说配置过程较为复杂,需要开发者对 ShardingSphere-JDBC 的配置参数有一定的了解。
ShardingSphere-JDBC-Core-Spring-Boot-Starter:在依赖方面,除了引入 ShardingSphere-JDBC 的相关依赖外,还需要引入 Spring Boot 的相关依赖。在配置上,它借助 Spring Boot 的配置机制,通过在application.properties或application.yml文件中配置相关属性,就可以完成 ShardingSphere-JDBC 的大部分配置工作,配置相对简单直观。

直接上干货
目前开发环境为Springcloud ,springBoot配置文件是一致的 yml文件
这里我是由若依的多数据源分片算法改动而来
推荐0基础的先去跟着若依提供的跟着去配置一遍,比较容易理解我这块自定义的
原文多数据源集成分库分表

# spring配置
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    db: 3
    timeout: 2000
    #分库分表的自定义配置
  shardingsphere:
    datasource:
      ds0:
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.zaxxer.hikari.HikariDataSource
        username: root
        password: root
        jdbc-url: jdbc:mysql://11.11.11.11:3306/ry-log?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
      names: ds0
    props:
      sql-show: true
    rules:
      sharding:
        binding-tables: sys_oper_log
        # 分布式序列算法配置 这里只是配置雪花算法
        key-generators:
          snowflake:
            type: SNOWFLAKE
            props:
              worker-id: 123
        sharding-algorithms:
          table-classbased:
            props:
              strategy: standard
              # 自定义标准分配算法
              algorithmClassName: com.ruoyi.system.config.MyTableHintShardingAlgorithm
            type: CLASS_BASED
        tables:
          sys_oper_log:
          	##我这里是单库分表
            actual-data-nodes: ds0.sys_oper_log_GET,ds0.sys_oper_log_PUT
            # biu在这里配置好主键id 雪花算法才会启用  当然表主键需要设置为not null 不自动增长
            key-generate-strategy:
              column: oper_id
              key-generator-name: snowflake
            table-strategy:
              standard:
                sharding-algorithm-name: table-classbased ##上面设置的自定义分片方法
                sharding-column: request_method      ## 分片字段
   ##正常的数据库资源池             
  datasource:
    druid:
      stat-view-servlet:
        enabled: true
        loginUsername: admin
        loginPassword: 123456
    dynamic:
      druid:
        initial-size: 5
        min-idle: 5
        maxActive: 20
        maxWait: 60000
        connectTimeout: 30000
        socketTimeout: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,slf4j
        connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
      datasource:
        # 主库数据源
        master:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://11.11.11.11:3306/agrocloud_ecology_cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
          username: root
          password: root
        # 从库数据源
        order:
          username: root
          password: root
          url: jdbc:mysql://11.11.11.11:3306/ry-order?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
          driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis配置
mybatis:
  # 搜索指定包别名
  typeAliasesPackage: com.ruoyi.system
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapperLocations: classpath:mapper/**/*.xml

# swagger配置
swagger:
  title: 系统模块接口文档
  license: Powered By ruoyi
  licenseUrl: https://ruoyi.vip

maven配置
若依框架的要把 ruoyi-common-datasource 注释掉!!!

  <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.33</version>
        </dependency>


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

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.23</version>
        </dependency>

                <!-- dynamic多数据源  -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>

配置多数据源,使分库分表与德鲁连接池接共存

import java.util.Map;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;

/**
 * 动态数据源配置
 *
 * @author ruoyi
 */
@Configuration
@Lazy
public class DataSourceConfiguration
{
    /**
     * 分表数据源名称
     */
    private static final String SHARDING_DATA_SOURCE_NAME = "sharding";

    /**
     * 动态数据源配置项
     */
    @Autowired
    private DynamicDataSourceProperties properties;

    /**
     * shardingjdbc有四种数据源,需要根据业务注入不同的数据源
     *
     * <p>1. 未使用分片, 脱敏的名称(默认): shardingDataSource;
     * <p>2. 主从数据源: masterSlaveDataSource;
     * <p>3. 脱敏数据源:encryptDataSource;
     * <p>4. 影子数据源:shadowDataSource
     *
     */
    @Resource
    private DataSource shardingSphereDataSource;

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider()
    {
        Map<String, DataSourceProperty> datasourceMap = properties.getDatasource();
        return new AbstractDataSourceProvider()
        {
            @Override
            public Map<String, DataSource> loadDataSources()
            {
                Map<String, DataSource> dataSourceMap = createDataSourceMap(datasourceMap);
                // 将 shardingjdbc 管理的数据源也交给动态数据源管理
                dataSourceMap.put(SHARDING_DATA_SOURCE_NAME, shardingSphereDataSource);
                return dataSourceMap;
            }
        };
    }

    /**
     * 将动态数据源设置为首选的
     * 当spring存在多个数据源时, 自动注入的是首选的对象
     * 设置为主要的数据源之后,就可以支持shardingjdbc原生的配置方式了
     */
    @Primary
    @Bean
    public DataSource dataSource()
    {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrict(properties.getStrict());
        dataSource.setStrategy(properties.getStrategy());
        dataSource.setP6spy(properties.getP6spy());
        dataSource.setSeata(properties.getSeata());
        return dataSource;
    }
}

自定义分库分表实现类


import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;
import java.util.Properties;


public class MyTableHintShardingAlgorithm implements StandardShardingAlgorithm<String> {
    private Properties props = new Properties();

    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<String> shardingValue) {
        for (String tableName : tableNames) {
            System.out.println("表名称========================"+tableName);
            System.out.println("列值名称========================"+shardingValue.getValue());
            /**
             * 取模算法,分片健 % 表数量
             */
            String value = shardingValue.getValue().substring(0,2);
            if (tableName.contains(value)) {
                return tableName;
            }
        }
        throw new IllegalArgumentException();
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) {
        return collection;
    }

    @Override
    public Properties getProps() {
        return this.props;
    }

    @Override
    public void init(Properties properties) {

    }
}

在这里插入图片描述
使用的时候加上注解@DS(“sharding”)即可 实体类无特殊配置,想使用雪花自增id 必须取消掉mysql的自增id
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

boJIke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值