springboot+shardingsphere+mybatis-plus

工作中经常遇到大数据量的问题,每天的数据量可达百万,需要进行分库分表,从网上找了很多博客学习,经常遇到各种各样的问题,大都是版本选择和配置文件错误,其实仔细研究官方文档就可以了,今天总算是跑起来了,测试也没什么大问题,后面继续优化。

一、框架版本

1、shardingsphere5.5.0

2、springboot3.2.11

3、mybatis-plus3.5.5

二、maven依赖

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

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

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

        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>shardingsphere-jdbc</artifactId>
            <version>5.5.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.shardingsphere</groupId>
                    <artifactId>shardingsphere-test-util</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

三、配置文件(application.yml)

spring:
  main:
    allow-bean-definition-overriding: true
  application:
    name: ls-backend
  datasource:
    driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
    url: jdbc:shardingsphere:classpath:sharding1.yaml
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB
server:
  port: 8085
  servlet:
    context-path: /
    encoding:
      force-response: true


#Mybatis扫描
mybatis:
  config-location: classpath:/mybatis-config.xml

mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

四、sharding配置文件(sharding.yaml)

dataSources:
  ds0:
    driverClassName: com.mysql.cj.jdbc.Driver
    dataSourceClassName: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/ds0?useUnicode=true&useSSL=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
    username: root
    password: root
  ds1:
    driverClassName: com.mysql.cj.jdbc.Driver
    dataSourceClassName: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/ds1?useUnicode=true&useSSL=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8
    username: root
    password: root
rules:
- !SHARDING
  tables:
    flight:
      actualDataNodes: ds0.flight_$->{0..1}
      tableStrategy:
        standard:
          shardingColumn: id
          shardingAlgorithmName: flight-id-inline
  shardingAlgorithms:
    flight-id-inline:
      type: INLINE
      props:
        algorithm-expression: flight_$->{id % 2}
props:
  sql-show: true

这块要特别注意,属性名要严格遵守驼峰,"- !SHARDING"必须要加,目前不明白为什么,这块是完全按照官方文档来的,还有就是官方文档中写的url是jdbcUrl,但是运行会报错,dubug发现这块取url时使用的是url,故将此处改为url可正常运行。

五、测试

使用mybatis-plus新增数据,根据日志可发现shardingsphere会根据分片算法将逻辑表名变更为实际表名。日志如下:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@165b679a] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@412916513 wrapping org.apache.shardingsphere.driver.jdbc.core.connection.ShardingSphereConnection@5ece1773] will not be managed by Spring
==>  Preparing: SELECT id,num,date FROM flight WHERE id=?
==> Parameters: 2(Integer)
2024-11-06T10:55:42.313+08:00  INFO 9892 --- [ls-backend] [nio-8085-exec-4] ShardingSphere-SQL                       : Logic SQL: SELECT id,num,date FROM flight WHERE id=?
2024-11-06T10:55:42.313+08:00  INFO 9892 --- [ls-backend] [nio-8085-exec-4] ShardingSphere-SQL                       : Actual SQL: ds0 ::: SELECT id,num,date FROM flight_0 WHERE id=? ::: [2]
<==    Columns: id, num, date
<==        Row: 2, 2, 2024-11-06 10:35:02
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@165b679a]

flight逻辑表名会根据取模算法替换为实际表名。

结语

遇到问题不要慌,静下心来看看文档,多看看框架源代码。

这是第一次接触shardingsphere,有很多详细问题没有理解透彻,大佬勿喷!!!

Spring Boot 3.4.0 中整合 ShardingSphere 5.5.2 和 MyBatis-Plus 实现分库分表的解决方案,需要结合 ShardingSphere 的分片策略配置以及 MyBatis-Plus 提供的便捷操作数据库的能力。以下是实现步骤: ### 1. 添加依赖 首先,在 `pom.xml` 中引入 Spring BootShardingSphereMyBatis-Plus 相关依赖: ```xml <dependencies> <!-- Spring Boot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3</version> </dependency> <!-- ShardingSphere JDBC --> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId> <version>5.5.2</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> </dependencies> ``` ### 2. 配置 ShardingSphere 分片规则 在 `application.yml` 中配置 ShardingSphere 的分库分表规则: ```yaml spring: shardingsphere: datasource: names: ds0,ds1 ds0: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ds0?useSSL=false&serverTimezone=UTC username: root password: root ds1: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ds1?useSSL=false&serverTimezone=UTC username: root password: root rules: sharding: tables: user: actual-data-nodes: ds$->{0..1}.user_$->{0..1} table-strategy: standard: sharding-column: user_id sharding-algorithm-name: user-table-inline key-generator: column: user_id type: SNOWFLAKE sharding-algorithms: user-table-inline: type: INLINE props: algorithm-expression: user_$->{user_id % 2} ``` ### 3. 创建实体类与 Mapper 接口 创建实体类 `User` 并使用 MyBatis-Plus 注解映射字段: ```java import com.baomidou.mybatisplus.annotation.*; @TableName("user") public class User { @TableId(value = "user_id", type = IdType.ASSIGN_ID) private Long userId; @TableField("name") private String name; @TableField("age") private Integer age; // Getter and Setter } ``` 定义 `UserMapper` 接口并继承 `BaseMapper`: ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface UserMapper extends BaseMapper<User> { } ``` ### 4. 配置 MyBatis-Plus 在配置类中启用 MyBatis-Plus 功能: ```java import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Configuration; @Configuration @MapperScan("com.example.mapper") public class MyBatisPlusConfig { } ``` ### 5. 使用 MyBatis-Plus 进行数据库操作 在 Service 层中使用 `UserMapper` 进行业务操作: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; public void addUser(User user) { userMapper.insert(user); } public List<User> getAllUsers() { return userMapper.selectList(null); } } ``` ### 6. 验证分库分表功能 编写测试类或通过 `@SpringBootTest` 验证数据是否正确插入到对应的分片表中,并确保查询操作能够跨库分表获取数据。 ### 7. 注意事项 - **绑定表配置**:如果存在主从表关系,应配置绑定表,以确保主表与子表的分片策略一致,避免跨库关联查询的问题[^3]。 - **依赖冲突**:由于 ShardingSphereMyBatis-Plus 都可能引入 MyBatis,因此需要注意依赖冲突问题,可以通过 `exclusion` 排除重复依赖[^4]。 --- ###
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值