gpt4 book ai didi

java - 如何对AbstractRoutingDataSource进行安全频繁的DataSource切换?

转载 作者:行者123 更新时间:2023-12-02 07:50:08 27 4
gpt4 key购买 nike

我根据this article为Spring+Hibernate实现了动态数据源路由。我有几个具有相同结构的数据库,我需要选择哪个数据库将运行每个特定查询。

在本地主机上一切正常,但我担心这在真实的网站环境中如何保持。他们使用一些静态上下文持有者来确定使用哪个数据源:

public class  CustomerContextHolder {

private static final ThreadLocal<CustomerType> contextHolder =
new ThreadLocal<CustomerType>();

public static void setCustomerType(CustomerType customerType) {
Assert.notNull(customerType, "customerType cannot be null");
contextHolder.set(customerType);
}

public static CustomerType getCustomerType() {
return (CustomerType) contextHolder.get();
}

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

它被包装在某个 ThreadLocal 容器中,但这到底意味着什么?当两个网络请求并行调用这段代码时会发生什么:

CustomerContextHolder.setCustomerType(CustomerType.GOLD);
//<another user will switch customer type here to CustomerType.SILVER in another request>
List<Item> goldItems = catalog.getItems();

在 Spring MVC 中,每个 Web 请求都包装到自己的线程中吗?其他 Web 用户可以看到 CustomerContextHolder.setCustomerType() 更改吗?我的 Controller 有 synchronizeOnSession=true

如何确保在我为当前用户运行所需的查询之前没有其他人会切换数据源?

谢谢。

最佳答案

Is every web request wrapped into its own thread in Spring MVC?

是的,但这与Spring MVC无关,容器正在这样做(容器有一个线程池并选择其中一个来处理每个请求)。

Will CustomerContextHolder.setCustomerType() changes be visible to other web users?

没有。一个ThreadLocal根据定义是线程本地的。来自javadoc:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

您在 ThreadLocal设置的内容对其他线程不可见。你应该没问题

关于java - 如何对AbstractRoutingDataSource进行安全频繁的DataSource切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3048347/

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