SpinrgBoot + MybatisPlus 多租户整合

Posted on 2023-01-29 15:43  豆豆2018  阅读(408)  评论(0编辑  收藏  举报

 关于SpringBoot  整合 mybatisPlus 多租户的一点小实践。

https://github.com/doudou20188/mybatisPlus_TenantIdManager 简易项目,自行拉取参考。

上代码,蛮简单的,其实就是多配置一个拦截器,设置租户ID,这个操作可以取系统当前登陆信息,获取当前用户属于的租户。

 1 package com.example.book_crud.config;
 2 
 3 import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
 4 import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
 5 import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
 6 import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
 7 import com.example.book_crud.config.talent.TenantIdManager;
 8 import net.sf.jsqlparser.expression.Expression;
 9 import net.sf.jsqlparser.expression.LongValue;
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.context.annotation.Bean;
12 import org.springframework.context.annotation.Configuration;
13 
14 @Configuration
15 public class MybatisPlusConfig{
16 
17     /* 租户ID管理器 */
18     @Autowired
19     private TenantIdManager tenantIdManager;
20 
21 
22     @Bean
23     public MybatisPlusInterceptor mybatisPlusInterceptor(){
24         //定义mapper拦截器
25         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
26         //多租户插件
27         TenantLineInnerInterceptor tenantInterceptor = new TenantLineInnerInterceptor();
28         tenantInterceptor.setTenantLineHandler(new TenantLineHandler() {
29             @Override
30             public Expression getTenantId() {
31                 // 返回当前用户的租户ID
32                 return new LongValue(tenantIdManager.getCurrentTenantId());
33             }
34         });
35 
36 
37         //根据需求,添加需要的MP拦截器
38         //1分页插件
39 //        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
40         //乐观锁插件
41 //        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 乐观锁插件
42 
43         //2.多租户ID插件
44         interceptor.addInnerInterceptor(tenantInterceptor);
45         return interceptor;
46     }
47 }

我们尝试一下,查询的拦截,随便设置一下租户的ID:233

    @GetMapping
    public Result queryAll(){
        tenantIdManager.setCurrentTenantId(233L);
        return new Result(true,bookService.list());
    }

拦截处理结果

==>  Preparing: SELECT id, type, name, description FROM tbl_book WHERE tenant_id = 233

可以看到,这里多帮助我们拼接了一个条件 

tenant_id = 233, 当前我们的表tbl_book 也需要额外加上该字段。实际使用过程中,需要根据业务情景使用,去判断是否需要进行租户的拦截处理。其实蛮简单的,类似乐观锁的操作。
需要注意的是,我们这里做的事同数据库的处理,是非物理隔离的。数据的隔离等级较低。
PS:才发现自己断更了好久,没沉淀了,如今重拾起来。加油。