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

SpringBoot + MyBatisPlus 实现多租户分库

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

引言

在如今的软件开发中,多租户(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结合,通过动态数据源实现多租户分库,是一种高效、灵活、易维护的解决方案,适用于多租户系统的开发。可以有效地保护租户数据安全,提高系统性能,同时具有良好的可扩展性和可维护性。

相关推荐

Linux高性能服务器设计

C10K和C10M计算机领域的很多技术都是需求推动的,上世纪90年代,由于互联网的飞速发展,网络服务器无法支撑快速增长的用户规模。1999年,DanKegel提出了著名的C10问题:一台服务器上同时...

独立游戏开发者常犯的十大错误

...

学C了一头雾水该咋办?

学C了一头雾水该怎么办?最简单的方法就是你再学一遍呗。俗话说熟能生巧,铁杵也能磨成针。但是一味的为学而学,这个好像没什么卵用。为什么学了还是一头雾水,重点就在这,找出为什么会这个样子?1、概念理解不深...

C++基础语法梳理:inline 内联函数!虚函数可以是内联函数吗?

上节我们分析了C++基础语法的const,static以及this指针,那么这节内容我们来看一下inline内联函数吧!inline内联函数...

C语言实战小游戏:井字棋(三子棋)大战!文内含有源码

井字棋是黑白棋的一种。井字棋是一种民间传统游戏,又叫九宫棋、圈圈叉叉、一条龙、三子旗等。将正方形对角线连起来,相对两边依次摆上三个双方棋子,只要将自己的三个棋子走成一条线,对方就算输了。但是,有很多时...

C++语言到底是不是C语言的超集之一

C与C++两个关系亲密的编程语言,它们本质上是两中语言,只是C++语言设计时要求尽可能的兼容C语言特性,因此C语言中99%以上的功能都可以使用C++完成。本文探讨那些存在于C语言中的特性,但是在C++...

在C++中,如何避免出现Bug?

C++中的主要问题之一是存在大量行为未定义或对程序员来说意外的构造。我们在使用静态分析器检查各种项目时经常会遇到这些问题。但正如我们所知,最佳做法是在编译阶段尽早检测错误。让我们来看看现代C++中的一...

ESL-通过事件控制FreeSWITCH

通过事件提供的最底层控制机制,允许我们有效地利用工具箱,适时选择使用其中的单个工具。FreeSWITCH是一个核心交换与混合矩阵,它周围有几十个模块提供各种功能特性。我们完全控制了所有的即时信息,这些...

物理老师教你学C++语言(中篇)

一、条件语句与实验判断...

C语言入门指南

当然!以下是关于C语言入门编程的基础介绍和入门建议,希望能帮你顺利起步:C语言入门指南...

C++选择结构,让程序自动进行决策

什么是选择结构?正常的程序都是从上至下顺序执行,这就是顺序结构...

C++特性使用建议

1.引用参数使用引用替代指针且所有不变的引用参数必须加上const。在C语言中,如果函数需要修改变量的值,参数必须为指针,如...

C++程序员学习Zig指南(中篇)

1.复合数据类型结构体与方法的对比C++类:...

研一自学C++啃得动吗?

研一自学C++啃得动吗?在开始前我有一些资料,是我根据网友给的问题精心整理了一份「C++的资料从专业入门到高级教程」,点个关注在评论区回复“888”之后私信回复“888”,全部无偿共享给大家!!!个人...

C++关键字介绍

下表列出了C++中的常用关键字,这些关键字不能作为变量名或其他标识符名称。1、autoC++11的auto用于表示变量的自动类型推断。即在声明变量的时候,根据变量初始值的类型自动为此变量选择匹配的...