shardingsphere+springboot+mybatis 分库分表

一.前言

对于分库分表技术有很多,最近碰到一个需要对日志表按月切割,一个非常典型的横向切割数据库表的场景,在集成shardingsphere碰到了很多坑在此会说一下
官方文档地址

https://shardingsphere.apache.org/document/current/cn/features/sharding/concept/configuration/

二.maven依赖

关键依赖

<?xml version="1.0" encoding="UTF-8"?>

<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>

    <groupId>com.hs</groupId>
    <artifactId>SpringBoot_Sharding</artifactId>
    <version>1.0.1</version>


    <name>SpringBoot_Sharding</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>

        <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
        <mysql-connector>5.1.39</mysql-connector>
        <fastjson>1.2.41</fastjson>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--druid数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
        </dependency>

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

    </dependencies>


    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!--运用SpringBoot 插件 使用spring-boot-devtools模块的应用,当classpath中的文件有改变时,会自动重启! -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

对于依赖需要说明下,依赖的版本号最好不好修改 因为shardingsphere与springboot部分版本是不兼容的,会存在项目无法启动的情况,并且shardingsphere是在数据库连接池技术之上的,所以连接池是一定要引入的,链接池不要引入start依赖格式引入 这种非自动启动注入的,因为项目启动shardingsphere会去加载自己的链接,如果别的连接池启动会有冲突,具体原因没有探究清楚

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

三.核心配置

# 引入配置文件
spring.profiles.active=log
server.port=8888
# 配置真实数据源
spring.shardingsphere.datasource.names=springboot0,springboot1

# 配置第 1 个数据源 注意数据源名称
#spring.shardingsphere.datasource.springboot0.type=com.alibaba.druid.pool.DruidDataSource
#spring.shardingsphere.datasource.springboot0.jdbc-url=jdbc:mysql://localhost:4806/springboot0?characterEncoding=utf-8&useSSL=false
spring.shardingsphere.datasource.springboot0.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.springboot0.url=jdbc:mysql://localhost:4806/springboot0?characterEncoding=utf-8&useSSL=false
spring.shardingsphere.datasource.springboot0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.springboot0.username=root
spring.shardingsphere.datasource.springboot0.password=WEAVERemobile7!@#

# 配置第 2 个数据源
#spring.shardingsphere.datasource.springboot1.type=com.alibaba.druid.pool.DruidDataSource
#spring.shardingsphere.datasource.springboot1.jdbc-url=jdbc:mysql://localhost:4806/springboot1?characterEncoding=utf-8&useSSL=false
spring.shardingsphere.datasource.springboot1.type=com.alibaba.druid.pool.DruidDataSource
spring.shardingsphere.datasource.springboot1.url=jdbc:mysql://localhost:4806/springboot0?characterEncoding=utf-8&useSSL=false
spring.shardingsphere.datasource.springboot1.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.springboot1.username=root
spring.shardingsphere.datasource.springboot1.password=WEAVERemobile7!@#

# 默认数据源,未分片的表默认执行库
spring.shardingsphere.sharding.default-data-source-name=springboot0

# 配置eb_msgpush_requestlog 表规则  
# $->{0..1}代表数据源springboot0-1  
spring.shardingsphere.sharding.tables.eb_msgpush_requestlog.actualDataNodes=springboot$->{0..1}.eb_msgpush_requestlog2021_0$->{3..4}

## 分片键 数据库字段 注意数据表eb_msgpush_requestlog
spring.shardingsphere.sharding.tables.eb_msgpush_requestlog.databaseStrategy.standard.shardingColumn=tenant_key
## 自定义 分库 算法:ClassName 为自定义算法类
spring.shardingsphere.sharding.tables.eb_msgpush_requestlog.databaseStrategy.standard.preciseAlgorithmClassName=com.example.algorithm.MyPreciseDBShardingAlgorithm

# 分表策略
## 分片键 数据库字段 注意数据表eb_msgpush_requestlog
spring.shardingsphere.sharding.tables.eb_msgpush_requestlog.tableStrategy.standard.shardingColumn=tenant_key
## 自定义 分库 算法:ClassName 为自定义算法类
spring.shardingsphere.sharding.tables.eb_msgpush_requestlog.tableStrategy.standard.preciseAlgorithmClassName=com.example.algorithm.MyPreciseTableShardingAlgorithm

# 打印执行的数据库以及语句
spring.shardingsphere.props.sql.show=true

#mybatis
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapperLocations=classpath:mapper/*.xml

4.分片算法(简答分片)

注意:分库分表算法的分片健 一定要注意与sql中where语句中的tenant_key条件一致 只有这样才会走分片算法 否则不会走

  select * from eb_msgpush_requestlog where data_type=#{dataType} and tenant_key=#{tenantKey}  and delete_type = 0

1.分库算法

/**
 * @PACKAGE_NAME: com.hs.algorithm
 * @ClassName: MyPreciseDBShardingAlgorithm
 * @Description: 自定义数据库的精确分片算法  按tenant_key分片
 * @Date: 2020-06-18 17:28
 **/
public class MyPreciseDBShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 数据分片
     *
     * @param dbNames              实际数据源集合; springboot0、springboot1
     * @param preciseShardingValue 分片键 preciseShardingValue 用户名值
     * @return
     */
    @Override
    public String doSharding(Collection<String> dbNames, PreciseShardingValue<String> preciseShardingValue) {
        String dbName = "e10-ebridge-" + preciseShardingValue.getValue();
        if(dbNames.contains(dbName)){
            return dbName;
        }

        throw new UnsupportedOperationException();
    }
}

2.分表算法

/**
 * @PACKAGE_NAME: com.hs.algorithm
 * @ClassName: MyPreciseTableShardingAlgorithm
 * @Description: 自定义表的精确分片算法,按月份分片
 * @Date: 2020-06-18 17:11
 **/
public class MyPreciseTableShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy_MM");


    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> preciseShardingValue) {
        String targetTable = preciseShardingValue.getLogicTableName() + LocalDate.now().format(formatter);
        if (availableTargetNames.contains(targetTable)){
            return targetTable;
        }
        throw new UnsupportedOperationException("无效的表名称: " + targetTable);
    }
}

源码地址
https://github.com/2250749979/shardingspheredemo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我可以为你提供一些关于使用SpringBoot ShardingJDBC MyBatis进行分库分表的建议,例如:1. 使用ShardingSphere框架定义数据库分片策略;2. 使用MyBatis实现MyBatis SQL脚本;3. 使用SpringBoot注解的方式定义数据源和ShardingJDBC的配置。 ### 回答2: 使用SpringBoot ShardingJDBC和MyBatis可以很方便地实现分库分表功能。首先,ShardingJDBC是一个轻量级的数据库中间件,可以将数据分散到不同的数据库实例中,从而实现分库的效果。其次,MyBatis是一个流行的持久层框架,可以通过XML或注解的方式与数据库进行交互。 在使用SpringBoot ShardingJDBC和MyBatis分库分表时,首先需要配置ShardingJDBC的数据源和分片规则。可以通过编写一个配置类来配置分库分表的规则,例如可以根据某个字段的取值来确定数据应该分散到哪个库或表中。配置完成后,就可以在MyBatis的Mapper接口中直接使用分库分表的数据源,从而实现对不同数据库或表的访问。 在编写Mapper接口时,可以使用MyBatis提供的注解或XML方式来编写SQL语句。在SQL语句中,可以使用ShardingJDBC提供的分片键来实现对特定库或表的访问。例如,在需要查询特定表的数据时,可以使用ShardingJDBC提供的Hint注解将查询操作路由到相应的表上。 总的来说,使用SpringBoot ShardingJDBC和MyBatis可以实现简单、高效的分库分表功能。通过配置ShardingJDBC的分片规则和使用MyBatis编写SQL语句,可以将数据分散到不同的数据库实例和表中,从而实现了水平扩展和负载均衡的效果。这种方式能够帮助我们提高数据库的性能和容量,从而更好地应对大规模的数据存储需求。 ### 回答3: 使用SpringBoot ShardingJDBC MyBatis可以轻松实现分库分表。 首先,ShardingJDBC是一个分库分表的开源框架,它可以通过数据库中间件实现数据的分散存储。而SpringBoot是一个快速构建项目的框架,可以帮助开发者轻松集成各种组件。 使用SpringBoot ShardingJDBC MyBatis进行分库分表,首先需要配置ShardingJDBC的数据源、分片策略以及分表策略。可以通过配置文件或者编程方式来完成配置。配置数据源时,可以指定多个数据库的连接信息,并使用分片策略将数据分配到不同的数据库中。配置分表策略时,可以指定不同的分表规则,将数据根据一定的规则分散存储在不同的表中。 在具体的业务逻辑中,可以使用MyBatis来操作数据库。MyBatis是一个简化数据库访问的持久层框架,通过编写SQL语句和映射文件,可以轻松实现数据库的增删改查操作。 在访问数据库时,ShardingJDBC会根据配置的分片策略和分表策略,自动将数据路由到指定的数据库和表中。开发者不需要关心数据的具体存储位置,只需要使用MyBatis的API进行数据操作即可。 使用SpringBoot ShardingJDBC MyBatis进行分库分表,可以提高数据库的读写性能,增加数据的存储容量,并且可以实现数据的动态扩容和迁移。此外,由于SpringBootMyBatis的高度集成,开发者可以更加方便地进行开发和维护。 总之,使用SpringBoot ShardingJDBC MyBatis进行分库分表可以帮助开发者更好地管理数据,提升系统的性能和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值