目录
  • 正文
    • 技术框架
    • 租户Model设计
    • sql租户数据过滤
    • Hibernate filter
    • 分库
  • 结尾

    正文

    相信大家对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中。

    结尾

    到这里一个多租户的基础应用就搭建好了。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。