简体   繁体   中英

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. 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&amp;allowSlavesDownConnections=true&amp;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? 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. 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. I just marked my service tier with @Transactional(readOnly = true) and everything worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM