spring boot 集成shardingsphere + mybatis plus根据用户编号实现分库分表

注意:测试代码非上线环境,只供自我学习记录使用,如有商用出现任何问题,本人不承担任何责任。

简单说明:其实shardingsphere对于分库分表做了很好的实现,只是针对业务需要做特殊处理时需要开发人员对分库分表实现类进行自定义,所以可能这里是一些难点。本人前面已经有一篇文章根据账户表主键id取模,用户表创建时间的两种方式实现了分库分表。链接如下CSDN,本文主要针对使用用户编号的形式(根据用户id中的年月实现分库分表,以便后期根据用户id实现订单分库分表)

一,针对分裤分表的实现主要引用了shardingsphere + mybatis plus,具体pom文件配置关键信息如下:

 <!--shardingsphere start-->
        <!-- for spring boot -->
        <dependency>
            <groupId>io.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- for spring namespace -->
        <dependency>
            <groupId>io.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-namespace</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!--shardingsphere end-->
<!--Mybatis-Plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>

二,针对用户信息,创建数据库,用户表。因为很懒所以只创建了三个表,理应从01-09,10-12的。

三,根据用户表生成用户类,实体,mapper,service,controller,强烈建议使用user_info表自动化生成代码,不然你就会跟我一样体会到修改UserInfo01*.java的各种乐趣了。

四,剩下的就是大菜了。首先是mybatis plus配置

mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.type-aliases-package=com.tp.test
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

五, shardingsphere分库分表配置

//配置分库分表数据库名
sharding.jdbc.datasource.names=test2020,test2021

//配置数据对应的数据源链接池等数据库信息
sharding.jdbc.datasource.test2020.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.test2020.driver-class-name=com.mysql.cj.jdbc.Driver
sharding.jdbc.datasource.test2020.url=jdbc:mysql://localhost:3306/test2020?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
sharding.jdbc.datasource.test2020.username=root
sharding.jdbc.datasource.test2020.password=

//配置数据对应的数据源链接池等数据库信息
sharding.jdbc.datasource.test2021.type=com.alibaba.druid.pool.DruidDataSource
sharding.jdbc.datasource.test2021.driver-class-name=com.mysql.cj.jdbc.Driver
sharding.jdbc.datasource.test2021.url=jdbc:mysql://localhost:3306/test2021?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
sharding.jdbc.datasource.test2021.username=root
sharding.jdbc.datasource.test2021.password=



//配置user_info表分两个库,test01,test02,表从01-09,10-12
sharding.jdbc.config.sharding.tables.user_info.actual-data-nodes=test$->{2020..2021}.user_info_0$->{1..9},test$->{2020..2021}.user_info_1$->{0..2}
//分库字段是userId
sharding.jdbc.config.sharding.tables.user_info.database-strategy.standard.sharding-column=userId
//分库原则使用自定义类
sharding.jdbc.config.sharding.tables.user_info.database-strategy.standard.precise-algorithm-class-name=com.tp.test.config.DBShardingAlgorithm

//分表字段
sharding.jdbc.config.sharding.tables.user_info.table-strategy.standard.sharding-column=userId
//分表原则使用自定义类
sharding.jdbc.config.sharding.tables.user_info.table-strategy.standard.precise-algorithm-class-name=com.tp.test.config.TableShardingAlgorithm

//默认库 感觉可以不配置了
sharding.jdbc.config.sharding.default-database-strategy.standard.precise-algorithm-class-name=com.tp.test.config.DBShardingAlgorithm
//默认库分库字段
sharding.jdbc.config.sharding.default-database-strategy.standard.sharding-column=userId

六,自定义分库原则类,

@Slf4j
public class DBShardingAlgorithm implements PreciseShardingAlgorithm<String> {


    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        log.info("DBShardingAlgorithm PreciseShardingAlgorithm<String>");

        collection.stream().forEach((item) -> {
            log.info("actual node dbs:{}",item);
        });

        log.info("logic db mame : {}  rout column : {}",preciseShardingValue.getLogicTableName(),preciseShardingValue.getColumnName());

        log.info("logic column value : {}",preciseShardingValue.getValue());


        String userId = preciseShardingValue.getValue();

        String dbIndex = StringUtils.substring(userId,0,4);

        for (String item : collection){
            if(StringUtils.equalsIgnoreCase(item,"test"+dbIndex)){
                return item;
            }
        }
        throw new IllegalArgumentException();
    }

七,分表自定义类

@Slf4j
public class TableShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        log.info("TableShardingAlgorithm PreciseShardingAlgorithm<String>");

        collection.stream().forEach((item)->{
            log.info("actual node tables:{}",item);
        });


        log.info("logic table mame : {}  rout column : {}",preciseShardingValue.getLogicTableName(),preciseShardingValue.getColumnName());

        log.info("logic table value : {}",preciseShardingValue.getValue());

        String userId = preciseShardingValue.getValue();

        String tableIndex = StringUtils.substring(userId,4,6);

        for (String item:collection){
            if(StringUtils.equals(item,"user_info_"+tableIndex)){
                return item;
            }
        }
        throw new IllegalArgumentException();
    }

到这基本完成了所有的配置,但是如果现在开始测试,还是会遇见实体类不能创建的问题,因为还需要如下配置,该配置表示,spring允许同名bean;

spring.main.allow-bean-definition-overriding=true

 下面贴上测试结果:

1,用户编号20200130应该插入库test2020,表user_info_01

2,用户编号

 

到此全部结束,代码放在shardingsphere: 关于shardingsphere的各种测试用法 如有需要请自取

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库的实战代码: 1. 添加依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <dependencies> <!-- Sharding-JDBC --> <dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> </dependencies> ``` 2. 配置数据源 在 `application.yml` 文件中配置数据源: ```yaml spring: datasource: # 主库 master: url: jdbc:mysql://localhost:3306/db_master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # 从库 slave: url: jdbc:mysql://localhost:3306/db_slave?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 3. 配置 Sharding-JDBC 在 `application.yml` 文件中配置 Sharding-JDBC: ```yaml spring: shardingsphere: datasource: names: master, slave # 数据源名称 master: type: com.zaxxer.hikari.HikariDataSource slave: type: com.zaxxer.hikari.HikariDataSource config: sharding: tables: user: actualDataNodes: master.user_$->{0..1} # 分规则,user_0 和 user_1 tableStrategy: inline: shardingColumn: id algorithmExpression: user_$->{id % 2} # 分规则,根据 id 取模 databaseStrategy: inline: shardingColumn: id algorithmExpression: master # 分库规则,根据 id 取模 bindingTables: - user # 绑定,即需要进行分库 ``` 4. 配置 Mybatis-Plus 在 `application.yml` 文件中配置 Mybatis-Plus: ```yaml mybatis-plus: configuration: map-underscore-to-camel-case: true # 下划线转驼峰 ``` 5. 编写实体类 创建 `User` 实体类,用于映射数据库中的 `user` : ```java @Data public class User { private Long id; private String name; private Integer age; } ``` 6. 编写 Mapper 接口 创建 `UserMapper` 接口,用于定义操作 `user` 的方法: ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 7. 编写 Service 类 创建 `UserService` 类,用于调用 `UserMapper` 接口中的方法: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getById(Long id) { return userMapper.selectById(id); } public boolean save(User user) { return userMapper.insert(user) > 0; } public boolean updateById(User user) { return userMapper.updateById(user) > 0; } public boolean removeById(Long id) { return userMapper.deleteById(id) > 0; } } ``` 8. 测试 在 `UserController` 类中进行测试: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public User getUser(Long id) { return userService.getById(id); } @PostMapping("/user") public boolean addUser(@RequestBody User user) { return userService.save(user); } @PutMapping("/user") public boolean updateUser(@RequestBody User user) { return userService.updateById(user); } @DeleteMapping("/user") public boolean removeUser(Long id) { return userService.removeById(id); } } ``` 启动应用程序,访问 `http://localhost:8080/user?id=1` 可以得到 `id` 为 1 的用户信息。访问 `http://localhost:8080/user` 并传入用户信息,可以添加用户。访问 `http://localhost:8080/user` 并传入更新后的用户信息,可以更新用户信息。访问 `http://localhost:8080/user?id=1` 并使用 DELETE 方法,可以删除用户

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值