gpt4 book ai didi

spring - 我们如何在 Spring 调度程序中实现 Multi-Tenancy 选项?

转载 作者:行者123 更新时间:2023-12-05 07:42:28 26 4
gpt4 key购买 nike

我们在我们的应用程序中实现了 Multi-Tenancy 选项。每个租户都有各自独立的数据库。使用应用程序过滤器,我可以根据请求管理或分配每个租户。同样,我们如何在 spring boot 调度程序中做到这一点?

@component     
public class scheduler{
@Scheduled(fixedRate = 5000)
public void reminderEmail() {
//how can we fetch the exact data from exact tenant DB?
//since there is no request how can we get the tenant name for
fetching exact tenant db?
}
}

请让我知道我们怎样才能做到这一点?

最佳答案

类似于:

...
public class TenantContext {

private static final ThreadLocal<String> CONTEXT = new ThreadLocal<>();

public static void setTenantId(String tenantId) {
CONTEXT.set(tenantId);
}

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

然后您的 Filter 或 Spring MVC 拦截器可以在链接请求之前执行此操作:

String tenantId = request.getHeader(TENANT_HEADER_NAME);
TenantContext.setTenantId(tenantId);

并在回来的路上重置它:

TenantContext.setTenantId(null);

要在与 http 请求无关的线程中使用它,您可以这样做:

TenantContext.setTenantId("tenant_1");

更多信息可以在我的博文中找到 Multi-tenant applications using Spring Boot, JPA, Hibernate and Postgres

关于spring - 我们如何在 Spring 调度程序中实现 Multi-Tenancy 选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44521035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com