Springboot 多租户SaaS搭建方案
作者:soldier_n 时间:2022-06-04 00:23:32
相信大家对SaaS架构都有所了解,这里也不过多介绍,让我们直奔主题。
技术框架
springboot版本为2.3.4.RELEASE
持久层采用JPA
租户Model设计
因为saas应用所有租户都使用同个服务和数据库,为隔离好租户数据,这里创建一个BaseSaasEntity
public abstract class BaseSaasEntity {
@JsonIgnore
@Column(nullable = false, updatable = false)
protected Long tenantId;
}
里面只有一个字段tenantId,对应的就是租户Id,所有租户业务entity都继承这个父类。最后通过tenantId来区分数据是哪个租户。
sql租户数据过滤
按往常,表建好就该接着对应的模块的CURD。但saas应用最基本的要求就是租户数据隔离,就是公司B的人不能看到公司A的数据,怎么过滤呢,这里上面我们建立的BaseSaasEntity就起作用了,通过区分当前请求是来自那个公司后,在所有tenant业务sql中加上where tenant=?就实现了租户数据过滤。
Hibernate filter
如果让我们在业务中都去加上租户sql过滤代码,那工作量不仅大,而且出错的概率也很大。理想是过滤sql拼接统一放在一起处理,在租户业务接口开启sql过滤。因为JPA是有hibernate实现的,这里我们可以利用hibernate的一些功能
@MappedSuperclass
@Data
@FilterDef(name = "tenantFilter", parameters = {@ParamDef(name = "tenantId", type = "long")})
@Filter(condition = "tenant_id=:tenantId", name = "tenantFilter")
public abstract class BaseSaasEntity {
@JsonIgnore
@Column(nullable = false, updatable = false)
protected Long tenantId;
@PrePersist
public void onPrePersist() {
if (getTenantId() != null) {
return;
}
Long tenantId = TenantContext.getTenantId();
Check.notNull(tenantId, "租户不存在");
setTenantId(tenantId);
}
}
Hibernate3 提供了一种创新的方式来处理具有“显性(visibility)”规则的数据,那就是使用Hibernate 过滤器。Hibernate 过滤器是全局有效的、具有名字、可以带参数的过滤器,对于某个特定的 Hibernate session 您可以选择是否启用(或禁用)某个过滤器。
这里我们通过@FilterDef和@Filter预先定义了一个sql过滤条件。然后通过一个@TenantFilter注解来标识接口需要进行数据过滤
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Transactional
public @interface TenantFilter {
boolean readOnly() default true;
}
可以看出这个接口是放在方法上,对应的就是Controller层。@Transactional增加事务注解的意义是因为激活hibernate filter必须要开启事务,这里默认是只读事务。 最后定义一个切面来激活filter
@Aspect
@Slf4j
@RequiredArgsConstructor
public class TenantSQLAspect {
private static final String FILTER_NAME = "tenantFilter";
private final EntityManager entityManager;
@SneakyThrows
@Around("@annotation(com.lvjusoft.njcommon.annotation.TenantFilter)")
public Object aspect(ProceedingJoinPoint joinPoint) {
Session session = entityManager.unwrap(Session.class);
try {
Long tenantId = TenantContext.getTenantId();
Check.notNull(tenantId, "租户不存在");
session.enableFilter(FILTER_NAME).setParameter("tenantId", tenantId);
return joinPoint.proceed();
} finally {
session.disableFilter(FILTER_NAME);
}
}
}
这里切面的对象就是刚才自定义的@TenantFilter注解,在方法执行前拿到当前租户id,开启filter,这样租户数据隔离就大功告成了,只需要在租户业务接口上增加@TenantFilter注解即可, 开发只用关心业务代码。上图中的TenantContext是当前线程租户context,通过和前端约定好,接口请求头中增加租户id,服务端利用 * 把获取到的租户id缓存在ThreadLocal中
public class IdentityInterceptor extends HandlerInterceptorAdapter {
public IdentityInterceptor() {
log.info("IdentityInterceptor init");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader(AuthConstant.USER_TOKEN_HEADER_NAME);
UserContext.setToken(token);
String tenantId = request.getHeader(AuthConstant.TENANT_TOKEN_HEADER_NAME);
TenantContext.setTenantUUId(tenantId);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
UserContext.clear();
TenantContext.clear();
}
}
分库
随着租户数量的增加,mysql单库单表的数据肯定会达到瓶颈,这里只采用分库的手段。利用多数据源,将租户和数据源进行多对一的映射。
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
private Map<Object, Object> targetDataSources;
public DynamicRoutingDataSource() {
targetDataSources =new HashMap<>();
DruidDataSource druidDataSource1 = new DruidDataSource();
druidDataSource1.setUsername("username");
druidDataSource1.setPassword("password");
druidDataSource1.setUrl("jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf-8");
targetDataSources.put("db1",druidDataSource1);
DruidDataSource druidDataSource2 = new DruidDataSource();
druidDataSource2.setUsername("username");
druidDataSource2.setPassword("password");
druidDataSource2.setUrl("jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf-8");
targetDataSources.put("db2",druidDataSource1);
this.targetDataSources = targetDataSources;
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
public void addDataSource(String key, DataSource dataSource) {
if (targetDataSources.containsKey(key)) {
throw new IllegalArgumentException("dataSource key exist");
}
targetDataSources.put(key, dataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContext.getSource();
}
}
通过实现AbstractRoutingDataSource来声明一个动态路由数据源,在框架使用datesource前,spring会调用determineCurrentLookupKey()方法来确定使用哪个数据源。这里的DataSourceContext和上面的TenantContext类似,在 * 中获取到tenantInfo后,找到当前租户对应的数据源key并设置在ThreadLocal中。
结尾
到这里一个多租户的基础应用就搭建好了。
来源:https://juejin.cn/post/7109110335038029861
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JavaEE开发之SpringMVC中的自定义消息转换器与文件上传
![](https://img.aspxhome.com/file/2023/4/59504_0s.jpg)
利用spring的拦截器自定义缓存的实现实例代码
java中对list分页并显示数据到页面实例代码
Spring boot + mybatis + Vue.js + ElementUI 实现数据的增删改查实例代码(二)
![](https://img.aspxhome.com/file/2023/4/65724_0s.png)
带你了解Java数据结构和算法之数组
![](https://img.aspxhome.com/file/2023/7/83087_0s.png)
Spring Cache框架应用介绍
![](https://img.aspxhome.com/file/2023/2/57492_0s.png)
Java 中 synchronized的用法详解(四种用法)
C#不重复输出一个数组中所有元素的方法
![](https://img.aspxhome.com/file/2023/5/68085_0s.png)
Java 爬虫服务器被屏蔽的解决方案
![](https://img.aspxhome.com/file/2023/4/77124_0s.png)
vs2019永久配置opencv开发环境的方法步骤
![](https://img.aspxhome.com/file/2023/2/100302_0s.jpg)
Java选择排序和垃圾回收机制详情
基于java ssm springboot+mybatis酒庄内部管理系统设计和实现
![](https://img.aspxhome.com/file/2023/9/58449_0s.jpg)
Java基础之反射详解
![](https://img.aspxhome.com/file/2023/5/61955_0s.png)
Java8 CompletableFuture 异步多线程的实现
![](https://img.aspxhome.com/file/2023/8/57708_0s.jpg)
Spring MVC项目中的异常处理详解
![](https://img.aspxhome.com/file/2023/9/69929_0s.jpg)
解析Java和Eclipse中加载本地库(.dll文件)的详细说明
SpringBoot全局配置long转String丢失精度的问题解决
Spring中自定义数据类型转换的方法详解
springboot+vue制作后台管理系统项目
![](https://img.aspxhome.com/file/2023/4/69654_0s.png)
Java接口默认方法带来的问题分析【二义性问题】
![](https://img.aspxhome.com/file/2023/7/60117_0s.png)