shardingsphere-jdbc 按照租户(强制路由)分库+ springboot +MySQL

shardingsphere-jdbc 按照租户(强制路由)分库+ springboot +MySQL

pom.xml

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
	http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <!--<version>2.2.5.RELEASE</version>-->
        <version>1.5.5.RELEASE</version>
        <relativePath/>
    </parent>

	<groupId>com.example</groupId>
    <artifactId>test-shardingsphere</artifactId>
    <version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
    <description>Demo project for Spring Boot</description>

    <properties>
    </properties>

    <dependencies>
        <!--swagger ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--springboot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
        <!--sharding-jdbc-->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.1.0</version>
        </dependency>
        <!--mybatis starter-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
        <!--alibaba数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.12</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
        <!--aop-->
        <dependency>
                <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

springboot配置 application.properties

server.port=8090
spring.application.name=test-shardingSphere
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
spring.profiles.active=xml_config
#spring.profiles.active=class_config

springboot配置 application-class_config.properties

###如果使用这种方式,需要在启动类中加上exclude={DataSourceAutoConfiguration.class},如果使用配置文件方式,这个可加可不加
###奇怪的是我在MyConfig类上加@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})还是不行
spring.shardingsphere.enabled=false

spring.shardingsphere.tables=t_user,t_order_item,t_order
spring.shardingsphere.dataSourcesUrls=AG=jdbc:mysql://127.0.0.1:3306/order_db0?useUnicode=true&characterEncoding=utf-8&useSSL=false,ZW=jdbc:mysql://127.0.0.1:3306/order_db1?useUnicode=true&characterEncoding=utf-8&useSSL=false,QZ=jdbc:mysql://127.0.0.1:3306/order_db2?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.shardingsphere.dataSourcesUserNames=root,root,root
spring.shardingsphere.dataSourcesPasswords=123456,123456,123456

springboot配置 application-xml_config.properties

# 数据源名称 是逻辑名称,不一定和数据库名一样
spring.shardingsphere.datasource.names=AG, ZW, QZ

# 第一个数据源
spring.shardingsphere.datasource.AG.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.AG.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.AG.url=jdbc:mysql://127.0.0.1:3306/dsmsxf?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.shardingsphere.datasource.AG.username=root
spring.shardingsphere.datasource.AG.password=123456


# 第二个数据源
spring.shardingsphere.datasource.ZW.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.ZW.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ZW.url=jdbc:mysql://127.0.0.1:3306/dst001?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.shardingsphere.datasource.ZW.username=root
spring.shardingsphere.datasource.ZW.password=123456

# 第三个数据源
spring.shardingsphere.datasource.QZ.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.QZ.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.QZ.url=jdbc:mysql://127.0.0.1:3306/dst002?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.shardingsphere.datasource.QZ.username=root
spring.shardingsphere.datasource.QZ.password=123456

# 默认数据源,不涉及分表的表会使用这个数据源
spring.shardingsphere.sharding.default-data-source-name=AG
# 需要分库的表,如果不配置这些,所有数据将会直接路由到默认数据源
spring.shardingsphere.sharding.tables.t_user.actual-data-nodes=AG.t_user,ZW.t_user,QZ.t_user
spring.shardingsphere.sharding.tables.t_order_item.actual-data-nodes=AG.t_order_item,ZW.t_order_item,QZ.t_order_item
spring.shardingsphere.sharding.tables.t_order.actual-data-nodes=AG.t_order,ZW.t_order,QZ.t_order

spring.shardingsphere.sharding.default-database-strategy.hint.algorithm-class-name=com.config.MyPreciseShardingAlgorithm2

# 开启sql显示
spring.shardingsphere.props.sql.show=true

init.sql

CREATE TABLE `t_order` (
  `id`  bigint(20) unsigned NOT NULL  COMMENT '主键id',
  `config_id`  bigint(20) unsigned NOT NULL  COMMENT '',
  `order_name` varchar(111) NOT NULL COMMENT '',
  PRIMARY KEY (`id`)
);

CREATE TABLE `t_order_item` (
  `id`  bigint(20) unsigned NOT NULL  COMMENT '主键id',
  `order_id`  bigint(20) unsigned NOT NULL  COMMENT '',
  `dict_id`  bigint(20) unsigned NOT NULL  COMMENT '',
  `item_name` varchar(111) NOT NULL COMMENT '',
  PRIMARY KEY (`id`)
);
CREATE TABLE `t_config` (
  `id`  bigint(20) unsigned NOT NULL  COMMENT '主键id',
  `config_name` varchar(111) NOT NULL COMMENT '',
  PRIMARY KEY (`id`)
);

CREATE TABLE `t_dict` (
  `id`  bigint(20) unsigned NOT NULL  COMMENT '主键id',
  `dict_name` varchar(111) NOT NULL COMMENT '',
  PRIMARY KEY (`id`)
);

CREATE TABLE `t_user` (
  `id`  bigint(20) unsigned NOT NULL  COMMENT '主键id',
  `username` varchar(111) NOT NULL COMMENT '',
  PRIMARY KEY (`id`)
);

insert into t_config values (1,'配置1');
insert into t_config values (2,'配置2');
insert into t_dict values (1,'字典1');
insert into t_dict values (2,'字典2');
insert into t_user values (1,'用户1');
insert into t_user values (2,'用户2');

MyConfig

@Configuration
@ConditionalOnProperty(prefix = "spring.shardingsphere", name = "enabled", havingValue = "false")
public class MyConfig {

    @Value("${spring.shardingsphere.tables}")
    private String tables;
    @Value("${spring.shardingsphere.dataSourcesUrls}")
    private String dataSourcesUrls;
    @Value("${spring.shardingsphere.dataSourcesUserNames}")
    private String dataSourcesUserNames;
    @Value("${spring.shardingsphere.dataSourcesPasswords}")
    private String dataSourcesPasswords;

    @Bean("dataSource")
    public DataSource shardingDataSource() throws SQLException {
        // 配置真实数据源
        String []urls= dataSourcesUrls.split(",");
        String[] dbUserNames = dataSourcesUserNames.split(",");
        String[] dbPasswords = dataSourcesPasswords.split(",");
        Map<String, DataSource> dataSourceMap = new HashMap<>(urls.length);
        String defaultDs = "";
        for(int i=0;i<urls.length;i++){
            DruidDataSource ds = new DruidDataSource();
            String tid=urls[i].split("=")[0];
            String url=urls[i].split("=")[1];
            ds.setUrl(url);
            ds.setUsername(dbUserNames[i]);
            ds.setPassword(dbPasswords[i]);
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            dataSourceMap.put(tid, ds);
            if(i==0){
                defaultDs = tid;
            }
        }
        // 配置分片规则
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.setDefaultDataSourceName(defaultDs);
        shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(new HintShardingStrategyConfiguration(new MyPreciseShardingAlgorithm2()));

        String []tbs= tables.split(",");
        for(String tb:tbs) {
            StringBuilder stringBuilder=new StringBuilder();
            dataSourceMap.forEach((k,v)->{
                stringBuilder.append(k);
                stringBuilder.append(".");
                stringBuilder.append(tb);
                stringBuilder.append(",");
            });
            TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration(tb,stringBuilder.substring(0, stringBuilder.length()-1));
            shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig);
        }
        
        Properties p = new Properties();
        p.setProperty("sql.show",Boolean.TRUE.toString());
        // 获取数据源对象
        DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, p);
        return dataSource;
    }

}

MyPreciseShardingAlgorithm2

//强制路由,需要实现HintShardingAlgorithm接口
public class MyPreciseShardingAlgorithm2 implements HintShardingAlgorithm<String> {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> shardingValue) {
        Collection<String> values = shardingValue.getValues();
        return values;
    }
}

SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("分库分表").apiInfo(apiInfo())
                .protocols(Sets.newHashSet("http"))
                .select().apis(RequestHandlerSelectors.basePackage("com..controller"))
                .build().enable(true);
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("分库分表 - API").description("").termsOfServiceUrl("").version("5.0.0").build();
    }
}

ShardingJDBCAop

@Aspect
@Component
@EnableAspectJAutoProxy
public class ShardingJDBCAop {
    @Pointcut("execution(* com.mapper.*Mapper.*(..))")
    public void pc(){}

    /**
     * 注意:这里不能使用before搭档after这种
     * @param point
     * @return
     */
    @Around("pc()")
    public Object round(ProceedingJoinPoint point){
        HintManager hintManager = HintManager.getInstance();
        try{
            //这里可以根据登录session中租户标识进行动态设置值
            hintManager.setDatabaseShardingValue("ZW");
            return point.proceed();
        } catch (Throwable e) {
            throw new RuntimeException("异常了",e);
        } finally {
            hintManager.close();
        }
    }
}
<think>好的,我现在需要为用户介绍Sharding-JDBC分库和分表功能。首先,我应该回忆一下Sharding-JDBC的基本概念,它是Apache ShardingSphere的一个组件,主要用于数据库的分布式解决方案。分库分表是其核心功能之一,用来解决数据量过大导致的性能问题。 接下来,分库和分表的区别是什么?分库是将数据分散到不同的数据库中,每个数据库可以位于不同的服务器上,这样可以分担单个数据库的压力。分表则是将数据拆分到同一数据库的多个表中,或者不同数据库的表中,减少单表的数据量,提升查询效率。 需要解释分库分表的适用场景,比如数据量极大,单表超过千万行,或者并发量高导致数据库连接不够等情况。同时,也要提到可能的缺点,比如事务管理复杂,跨库join困难等。 然后,Sharding-JDBC如何实现分库分表?它通过解析SQL语句,根据配置的分片规则,将操作路由到对应的数据库或表中。用户需要配置数据源、分片策略、分片键等信息。分片策略包括标准分片策略、复合分片策略、行表达式分片策略等,可能需要举例说明,比如按用户ID取模分库,按时间范围分表。 还需要提到分库分表的常见策略,比如水平分片和垂直分片,不过Sharding-JDBC主要处理水平分片。水平分片的方式有范围分片、哈希分片、时间分片等。例如,用户表可以按用户ID的哈希值分成4个库,每个库再按月份分成12张表。 配置示例部分,可能需要给出一个简单的YAML配置,说明如何定义数据源,配置分库分表规则,比如分片键user_id,分库策略是user_id % 4,分表策略是order_id % 8。这样用户能更直观地理解。 还要强调Sharding-JDBC的特点,比如对应用透明,无需修改业务代码,只需配置;支持多种数据库,兼容大部分SQL语法;提供分布式事务支持,虽然可能有限制,但能处理大部分场景。 可能需要注意的问题,比如分片键的选择非常重要,要选择均匀分布的字段,避免数据倾斜。跨库查询的性能问题,建议在业务设计时尽量减少跨库join,或者通过其他手段如冗余字段来解决。 最后,总结分库分表的优势和使用Sharding-JDBC的好处,同时提醒用户根据实际业务需求设计合适的分片策略,避免过度设计。如果有必要,可以推荐官方文档或进一步的学习资源,帮助用户深入理解。</think>Sharding-JDBC 是 Apache ShardingSphere 的核心模块之一,主要用于实现关系型数据库的**分库分表**能力。以下是其分库分表功能的详细介绍: --- ### 一、核心概念 #### 1. 分库 (Database Sharding) - **定义**:将数据按规则分散到多个数据库实例中 - **目的**:突破单机数据库的存储/性能瓶颈,提高并发处理能力 - **典型场景**:用户数据按地区分布到不同地域的数据库 #### 2. 分表 (Table Sharding) - **定义**:将单个表数据拆分到多个物理表中 - **目的**:解决单表数据量过大导致的查询性能下降问题 - **典型场景**:订单表按月分表(order_202301, order_202302) --- ### 二、分片策略 #### 1. 分片键 (Sharding Key) - 数据路由的依据字段(如用户ID、订单时间等) - **选择原则**:高频查询条件、数据分布均匀 #### 2. 分片算法 | 类型 | 描述 | 示例 | |-------------------|----------------------------|-------------------------| | 标准分片算法 | 基于=、IN、BETWEEN的精确路由 | user_id % 4 | | 复合分片算法 | 多字段组合分片 | (user_id + order_id) % 8| | 行表达式分片 | 使用Groovy表达式 | ${user_id % 16} | | Hint分片 | 强制路由 | 通过代码指定库表 | --- ### 三、配置示例(YAML) ```yaml spring: shardingsphere: datasource: names: ds0, ds1 ds0: # 数据源0配置 type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://localhost:3306/db0 username: root password: root ds1: # 数据源1配置 # ...类似配置... rules: sharding: tables: t_order: # 逻辑表名 actual-data-nodes: ds$->{0..1}.t_order_$->{0..7} # 物理表(2库×8表) database-strategy: # 分库策略 standard: sharding-column: user_id sharding-algorithm-name: db-sharding table-strategy: # 分表策略 standard: sharding-column: order_id sharding-algorithm-name: table-sharding sharding-algorithms: db-sharding: type: INLINE props: algorithm-expression: ds$->{user_id % 2} table-sharding: type: INLINE props: algorithm-expression: t_order_$->{order_id % 8} ``` --- ### 四、执行流程 1. **SQL解析**:解析SQL语义,提取分片键值 2. **路由计算**:根据分片规则确定目标库表 3. **SQL改写**:将逻辑SQL转换为真实物理SQL 4. **执行引擎**:多线程并行执行路由后的SQL 5. **结果归并**:合并多个数据源的返回结果 --- ### 五、注意事项 1. **事务管理**: - 单库事务自动支持 - 跨库事务建议使用Seata等分布式事务方案 2. **全局ID生成**: - 推荐使用Snowflake算法避免ID冲突 - 内置的Leaf-segment算法:`SHOW VARIABLES LIKE 'leaf.segment.url'` 3. **数据迁移**: - 使用弹性伸缩模块进行不停机迁移 - 校验命令:`CHECK SCALING jobId` --- ### 六、最佳实践 1. **冷热分离**:将历史数据归档到单独库表 2. **单元化路由**:按业务属性(如租户ID)进行分片 3. **避免全路由**:分片条件必须包含分片键 4. **索引优化**:每个分片表需单独建立索引 ```sql -- 通过Hint强制查询指定分片 /* ShardingSphere hint: shardingDataSourceValue=1 */ SELECT * FROM t_order WHERE ...; ``` --- 通过合理设计分库分表策略,Sharding-JDBC 可使系统轻松应对亿级数据量场景。建议结合具体业务特征进行压测验证,逐步优化分片方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值