[英]MySql Master/Slave Spring Hibernate with com.mysql.jdbc.ReplicationDriver
I have a web application that uses spring (4.2.9.RELEASE), hibernate (5.1.3.Final), with the mysql replication driver, running on Tomcat. 我有一个Web应用程序,它在Tomcat上运行使用spring(4.2.9.RELEASE),hibernate(5.1.3.Final)和mysql复制驱动程序。 All queries are going to the master and none are going to the replicas. 所有查询都将转到主数据库,而所有查询都不会转到副本数据库。 Here is my resource in my context: 这是我的背景资源:
<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&allowSlavesDownConnections=true&readFromMasterWhenNoSlaves=true"
validationQuery="SELECT 1"/>
In my service layer, I have the my read-only methods setup like this... 在我的服务层中,我有这样的只读方法设置...
@Override
@Transactional(readOnly = true)
public List<Location> getAll(long customerId) {
return dao.getAll(customerId);
}
When calling this method (as the entry-point) all my queries go to the master and not the slave. 当调用此方法(作为入口点)时,我所有的查询都转到主数据库而不是从数据库。
I have been searching for an answer to this and I believe the issue is that hibernate is not setting the underlying connection to read-only, thus the replication driver is sending all queries to the master. 我一直在寻找答案,我认为问题在于休眠状态未将基础连接设置为只读,因此复制驱动程序会将所有查询发送给主服务器。 So my question is, should spring/hibernate be setting the connection to readOnly or do I need to do this with AOP or similar? 所以我的问题是,spring / hibernate应该将连接设置为readOnly还是我需要用AOP或类似的工具来做到这一点? It seems that some posts say that it should set the connect to read only while others say it doesn't. 似乎有些帖子说应该将连接设置为只读,而其他帖子则说不可以。 Can someone clarify for me so I can hopefully fix my issue. 有人可以帮我澄清一下,希望我可以解决我的问题。 Thanks in advance! 提前致谢!
So it turns out that everything works perfectly when you use straight JPA. 因此,事实证明,当您使用直接JPA时,一切都可以完美运行。 This application was still using Hibernate's SessionFactory, so when I switched everything to EntityManager everything worked without any need for AOP to intercept connection acquisitions. 该应用程序仍在使用Hibernate的SessionFactory,因此当我将所有内容切换到EntityManager时,所有内容都可以运行,而无需AOP来拦截连接获取。 I just marked my service tier with @Transactional(readOnly = true) and everything worked. 我只是用@Transactional(readOnly = true)标记了我的服务层,并且一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.