百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

SpringBoot + MyBatisPlus 实现多租户分库

wptr33 2024-12-15 17:12 71 浏览

引言

在如今的软件开发中,多租户(Multi-Tenancy)应用已经变得越来越常见。多租户是一种软件架构技术,它允许一个应用程序实例为多个租户提供服务。每个租户都有自己的数据和配置,但应用程序实例是共享的。而在我们的Spring Boot + MyBatis Plus环境中,我们可以利用动态数据源来实现多租户分库。

实现原理

SpringBoot + MyBatisPlus 动态数据源实现多租户分库的原理主要是通过切换不同的数据库连接来实现。对于每个租户,应用程序会使用一个独立的数据库连接,这样每个租户就拥有了自己的数据隔离空间。具体来说,当我们创建一个新的租户时,我们同时也为这个租户创建一个新的数据库连接。这些数据库连接被存储在一个数据源工厂中,我们可以根据租户的ID或者其他唯一标识符来获取对应的数据库连接。当一个租户需要访问其数据时,我们从数据源工厂中获取该租户对应的数据库连接,然后使用这个连接来执行数据库操作。

示例代码

在pom.xml中添加依赖

确保你的 `pom.xml` 中包含了以下依赖:

<dependencies>
    <!-- Spring Boot Web Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- MyBatis Plus Starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.3.3</version> <!-- 替换为最新版本 -->
    </dependency>

    <!-- Druid 数据源 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.6</version> <!-- 替换为最新版本 -->
    </dependency>

    <!-- MySQL 驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

接下来,我们按步骤创建一个多租户分库的示例:

数据库表结构

创建一个数据库表来存储多租户的数据源配置信息。

CREATE TABLE tenant_datasource (

    tenant_id VARCHAR(50) PRIMARY KEY,
    url VARCHAR(255),
    username VARCHAR(50),
    password VARCHAR(50)
);

数据源配置

在 `application.properties` 或 `application.yml` 中配置默认的数据源信息。

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/default_db
    username: root
    password: root

实现动态数据源配置

创建一个动态数据源配置类,用于动态切换数据源。

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DynamicDataSourceProperties {

    private String url;
    private String username;
    private String password;
    // Getters and Setters
    // 根据配置创建数据源
    public DataSource createDataSource() {
        return DataSourceBuilder.create()
                .url(this.url)
                .username(this.username)
                .password(this.password)
                .build();
    }
}

创建动态数据源

创建一个动态数据源类,继承 `AbstractRoutingDataSource`,用于动态切换数据源。

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.getTenantId();
    }
}

创建租户上下文

创建一个租户上下文类,用于存储当前线程的租户标识。

public class TenantContext {

    private static ThreadLocal<String> tenantId = ThreadLocal.withInitial(() -> "default");

    public static String getTenantId() {
        return tenantId.get();
    }

    public static void setTenantId(String id) {
        tenantId.set(id);
    }

    public static void clear() {
        tenantId.remove();
    }
}

创建数据源管理器

创建一个数据源管理器,用于动态切换数据源。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
public class DataSourceManager {

    @Autowired
    private DynamicDataSourceProperties dynamicDataSourceProperties;
    private final Map<String, DataSource> dataSources = new HashMap<>();

    @PostConstruct
    public void init() {
        // 根据配置创建数据源并加入管理器
        dataSources.put("default", dynamicDataSourceProperties.createDataSource());
    }
    public void addDataSource(String tenantId, DataSource dataSource) {
        dataSources.put(tenantId, dataSource);
    }
    public DataSource getDataSource(String tenantId) {
        return dataSources.get(tenantId);
    }
}

创建数据源配置类

创建数据源配置类,用于配置动态数据源。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSourceConfig {

    @Autowired
    private DataSourceManager dataSourceManager;

    @Bean
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.putAll(dataSourceManager.getAllDataSources());
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(dataSourceManager.getDataSource("default"));
        return dynamicDataSource;
    }

    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
        return new DataSourceTransactionManager(dynamicDataSource);
    }
}

创建 MyBatis 配置

创建 MyBatis 配置类,配置 MyBatis Plus 的分页插件。

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

创建多租户数据源服务

创建多租户数据源服务类,用于初始化多租户数据源。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;

@Service
public class MultiTenantDataSourceService {

    @Autowired
    private DataSourceManager dataSourceManager;

    @Autowired
    private TenantDataSourceRepository tenantDataSourceRepository;

    @PostConstruct
    public void initialize() {
        List<TenantDataSource> tenantDataSources = tenantDataSourceRepository.findAll();
        for (TenantDataSource tenantDataSource : tenantDataSources) {
            DataSource dataSource = tenantDataSource.createDataSource();
            dataSourceManager.addDataSource(tenantDataSource.getTenantId(), dataSource);
        }
    }
}

创建多租户数据源实体类和 Repository

创建多租户数据源实体类和对应的 Repository 接口。

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tenant_datasource")
public class TenantDataSource {

    @Id
    @Column(name = "tenant_id")
    private String tenantId;

    private String url;

    private String username;

    private String password;

    // Getters and Setters

}
import org.springframework.data.jpa.repository.JpaRepository;

public interface TenantDataSourceRepository extends JpaRepository<TenantDataSource, String> {
}

创建业务服务类

创建一个业务服务类,用于处理业务逻辑。

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private DataSourceManager dataSourceManager;

    public User getUserById(Long id) {
        String tenantId = TenantContext.getTenantId();
        DataSource dataSource = dataSourceManager.getDataSource(tenantId);
        // 设置当前数据源
        DataSourceContextHolder.setDataSource(dataSource);
        return getById(id);
    }
}

创建 Controller

创建一个 Controller 用于测试多租户分库功能。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/user/{tenantId}/{userId}")
    public User getUser(@PathVariable String tenantId, @PathVariable Long userId) {
        // 切换租户
        TenantContext.setTenantId(tenantId);
        // 查询用户
        return userService.getUserById(userId);
    }
}

多租户数据源配置表

在数据库中插入多租户的数据源配置信息,例如:

INSERT INTO tenant_datasource (tenant_id, url, username, password)
VALUES ('tenant1', 'jdbc:mysql://localhost:3306/tenant1_db', 'root', 'password1');

INSERT INTO tenant_datasource (tenant_id, url, username, password)
VALUES ('tenant2', 'jdbc:mysql://localhost:3306/tenant2_db', 'root', 'password2');

测试多租户分库功能

启动 Spring Boot 应用程序,通过访问 http://localhost:8080/user/{tenantId}/{userId} 来测试多租户分库功能。这样就完成了一个简单的 Spring Boot + MyBatis Plus 多租户分库的示例。在实际项目中,你需要根据业务需求进一步完善和优化代码。如果有任何问题或需要进一步解释,请随时提出。

适用场景

1. 多租户系统开发:适用于多租户系统,每个租户有独立的数据库,通过动态数据源切换实现多租户数据隔离。

2. 租户级数据隔离:当多个租户共享同一应用但需要数据隔离时,可以通过此模式实现。

3. 灵活扩展:适用于系统需求可能动态扩展租户,每个租户有独立数据库的场景,不需修改系统架构。

优点

1. 数据隔离性强:每个租户有独立的数据库,数据隔离,保护租户数据安全。

2. 性能优化:每个租户有独立的数据库,避免多租户共享同一数据库的性能瓶颈。

3. 方便扩展:可以轻松实现动态增加新租户,每个租户有独立的数据库。

4. 可维护性高:MyBatisPlus提供了便捷的操作数据库的功能,减少开发人员的工作量。

5. 易用性强:Spring Boot集成MyBatisPlus,简化了配置和集成流程,提高开发效率。

总结

Spring Boot与MyBatisPlus结合,通过动态数据源实现多租户分库,是一种高效、灵活、易维护的解决方案,适用于多租户系统的开发。可以有效地保护租户数据安全,提高系统性能,同时具有良好的可扩展性和可维护性。

相关推荐

oracle数据导入导出_oracle数据导入导出工具

关于oracle的数据导入导出,这个功能的使用场景,一般是换服务环境,把原先的oracle数据导入到另外一台oracle数据库,或者导出备份使用。只不过oracle的导入导出命令不好记忆,稍稍有点复杂...

继续学习Python中的while true/break语句

上次讲到if语句的用法,大家在微信公众号问了小编很多问题,那么小编在这几种解决一下,1.else和elif是子模块,不能单独使用2.一个if语句中可以包括很多个elif语句,但结尾只能有一个...

python continue和break的区别_python中break语句和continue语句的区别

python中循环语句经常会使用continue和break,那么这2者的区别是?continue是跳出本次循环,进行下一次循环;break是跳出整个循环;例如:...

简单学Python——关键字6——break和continue

Python退出循环,有break语句和continue语句两种实现方式。break语句和continue语句的区别:break语句作用是终止循环。continue语句作用是跳出本轮循环,继续下一次循...

2-1,0基础学Python之 break退出循环、 continue继续循环 多重循

用for循环或者while循环时,如果要在循环体内直接退出循环,可以使用break语句。比如计算1至100的整数和,我们用while来实现:sum=0x=1whileTrue...

Python 中 break 和 continue 傻傻分不清

大家好啊,我是大田。...

python中的流程控制语句:continue、break 和 return使用方法

Python中,continue、break和return是控制流程的关键语句,用于在循环或函数中提前退出或跳过某些操作。它们的用途和区别如下:1.continue(跳过当前循环的剩余部分,进...

L017:continue和break - 教程文案

continue和break在Python中,continue和break是用于控制循环(如for和while)执行流程的关键字,它们的作用如下:1.continue:跳过当前迭代,...

作为前端开发者,你都经历过怎样的面试?

已经裸辞1个月了,最近开始投简历找工作,遇到各种各样的面试,今天分享一下。其实在职的时候也做过面试官,面试官时,感觉自己问的问题很难区分候选人的能力,最好的办法就是看看候选人的github上的代码仓库...

面试被问 const 是否不可变?这样回答才显功底

作为前端开发者,我在学习ES6特性时,总被const的"善变"搞得一头雾水——为什么用const声明的数组还能push元素?为什么基本类型赋值就会报错?直到翻遍MDN文档、对着内存图反...

2023金九银十必看前端面试题!2w字精品!

导文2023金九银十必看前端面试题!金九银十黄金期来了想要跳槽的小伙伴快来看啊CSS1.请解释CSS的盒模型是什么,并描述其组成部分。...

前端面试总结_前端面试题整理

记得当时大二的时候,看到实验室的学长学姐忙于各种春招,有些收获了大厂offer,有些还在苦苦面试,其实那时候的心里还蛮忐忑的,不知道自己大三的时候会是什么样的一个水平,所以从19年的寒假放完,大二下学...

由浅入深,66条JavaScript面试知识点(七)

作者:JakeZhang转发链接:https://juejin.im/post/5ef8377f6fb9a07e693a6061目录...

2024前端面试真题之—VUE篇_前端面试题vue2020及答案

添加图片注释,不超过140字(可选)...

今年最常见的前端面试题,你会做几道?

在面试或招聘前端开发人员时,期望、现实和需求之间总是存在着巨大差距。面试其实是一个交流想法的地方,挑战人们的思考方式,并客观地分析给定的问题。可以通过面试了解人们如何做出决策,了解一个人对技术和解决问...