java-如何为AbstractRoutingDataSource设置安全的频繁数据源开关?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-如何为AbstractRoutingDataSource设置安全的频繁数据源开关?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1933字,纯文字阅读大概需要3分钟。
内容图文
我根据this article为Spring Hibernate实现了动态数据源路由.我有几个结构相同的数据库,我需要选择哪个数据库将运行每个特定的查询.
一切都可以在localhost上正常运行,但是我担心这在真实的网站环境中将如何保持.他们正在使用一些静态上下文持有者来确定要使用的数据源:
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容器中,但这到底是什么意思?当两个Web请求并行调用这段代码时,会发生什么:
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请求是否都包装到其自己的线程中? CustomerContextHolder.setCustomerType()更改对其他Web用户可见吗?我的控制器具有syncnizeOnSession = 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
orset
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设置安全的频繁数据源开关?全部内容,希望文章能够帮你解决java-如何为AbstractRoutingDataSource设置安全的频繁数据源开关?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。