gpt4 book ai didi

java - 带有 com.mysql.jdbc.ReplicationDriver 的 MySql Master/Slave Spring Hibernate

转载 作者:行者123 更新时间:2023-11-30 21:58:46 24 4
gpt4 key购买 nike

我有一个使用 spring (4.2.9.RELEASE)、hibernate (5.1.3.Final) 和 mysql 复制驱动程序的 Web 应用程序,在 Tomcat 上运行。所有查询都将发送到主服务器,而不会发送到副本。这是我在上下文中的资源:

<Resource auth="Container" 
driverClassName="com.mysql.jdbc.ReplicationDriver"
defaultAutoCommit="false"
initialSize="3"
logAbandoned="false"
maxActive="200"
maxIdle="5"
maxWait="10000"
name="jdbc/powerptc"
removeAbandoned="true"
testOnBorrow="true"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
username="xxxxxxx"
password="xxxxxx"
url="jdbc:mysql:replication://localhost:3306,slave.test.net:3306/powerptc?autoReconnect=true&amp;allowSlavesDownConnections=true&amp;readFromMasterWhenNoSlaves=true"
validationQuery="SELECT 1"/>

在我的服务层中,我的只读方法设置如下...

@Override
@Transactional(readOnly = true)
public List<Location> getAll(long customerId) {
return dao.getAll(customerId);
}

当调用此方法(作为入口点)时,我所有的查询都会转到主服务器而不是从服务器。

我一直在寻找这个问题的答案,我认为问题是 hibernate 没有将底层连接设置为只读,因此复制驱动程序将所有查询发送到主服务器。所以我的问题是,spring/hibernate 应该将连接设置为 readOnly 还是我需要使用 AOP 或类似方法来执行此操作?似乎有些帖子说它应该将连接设置为只读,而其他人则说不应该。有人可以为我澄清一下,这样我就有希望解决我的问题。提前致谢!

最佳答案

事实证明,当您直接使用 JPA 时,一切都能完美运行。该应用程序仍在使用 Hibernate 的 SessionFactory,因此当我将所有内容切换到 EntityManager 时,一切正常,无需 AOP 拦截连接获取。我刚刚用 @Transactional(readOnly = true) 标记了我的服务层,一切正常。

关于java - 带有 com.mysql.jdbc.ReplicationDriver 的 MySql Master/Slave Spring Hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44135920/

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