Spring Security JPA的多租户 [英] Multitenancy with Spring security JPA

查看:980
本文介绍了Spring Security JPA的多租户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是此使用Spring JPA的多租户的后续操作

我选择使用"AbstractRoutingDataSource".但是现在的问题是在启动时初始化了数据源和entitymanager bean.春季是否有什么方法可以配置此功能,以便在用户通过身份验证后将其初始化?

I chose to use the 'AbstractRoutingDataSource'. But the problem is now datasource and entitymanager bean initialized at startup. is there anyway to configure this in spring which way that it will initialize after user is authenticated?

我能想到的另一个问题是如何处理并发性.我把tenantId放在这个班上

Another problem which i can think of will be how to handle concurrency. I put tenantId in this class

public class ThreadLocalContextUtil {
 private static final ThreadLocal<String> contextHolder =
            new ThreadLocal<String>();

   public static void setTenantId(String tenantId) {
      Assert.notNull(tenantId, "customerType cannot be null");
      contextHolder.set(tenantId);
   }

   public static String getTenantId() {
      return (String) contextHolder.get();
   }

   public static void clearTenant() {
      contextHolder.remove();
   }
}

我能想到的解决方案是在初始化数据源之后删除tenantId.正确吗?

The solution i can think of will be to remove the tenantId after the datasource is initialized. is that correct?

推荐答案

我已经解决了类似的问题.我基于Spring的AbstractDataSource实现了自己的TenantAwareDataSource.它从名为 tenantContext 的会话范围的Bean中获取 tenantId .每次处理传入请求时,都会更新此bean.这是通过使用Spring Security的安全过滤器完成的:

I've solved similar problem. I implemented my own TenantAwareDataSource based on Spring's AbstractDataSource. It takes tenantId from a session-scoped bean named tenantContext. This bean is updated every time the incoming request is processed. It is done by using Spring Security's security filter:

<security:http auto-config='false' >
    <security:custom-filter before="FIRST" ref="tenantFilter" />
    <!-- ...more security stuff... -->
</security:http>

我的TenantAwareDataSource是在启动时初始化的,但这并不重要,因为它创建为空-它不包含任何租户数据源(例如,池JDBC数据源或JPA实体管理器).当第一次为选定的租户调用getConnection()时,会懒惰地创建它们.

My TenantAwareDataSource is initialized in the startup time, but it does not matter because it is created empty - it contains no tenant datasources (e.g. pooled JDBC datasources or JPA entity manager). They are created lazily when the getConnection() is called for the first time for the selected tenant.

因此,我的TenantAwareDataSource维护自己的动态数据源映射,而AbstractRoutingDataSource希望在启动时对数据源映射进行静态初始化.

So, my TenantAwareDataSource maintains its own dynamic datasource map while AbstractRoutingDataSource expects static initializitaion of the datasource map done in the startup time.

在此文章中了解更多详细说明.

Read more detailed description in this article.

这篇关于Spring Security JPA的多租户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆