Springboot多租户SaaS如何搭建

这篇文章主要介绍“Springboot多租户SaaS如何搭建”,在日常操作中,相信很多人在Springboot多租户SaaS如何搭建问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Springboot多租户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中。

到此,关于“Springboot多租户SaaS如何搭建”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注蜗牛博客网站,小编会继续努力为大家带来更多实用的文章!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接