Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple consecutive transactions (different in read and write) correct routing missing spring setting #4

Open
alinturbut opened this issue Dec 29, 2021 · 3 comments

Comments

@alinturbut
Copy link

Hey,

As this code has proved to be useful in my endeavour to create a master-slave routing for a mysql read replica configuration and having wasted a few hours on trying to understand why after a read transaction, the next write transaction would go to the read replica, I've found a missing link in this code.

Spring, by default (in newer versions) uses handling_mode: IMMEDIATE_ACQUISITION_AND_HOLD which closes a database connection only on session close (therefor going to the read replica database for the next transaction after a read only transaction). In order to solve this, you need to pass the following application property: spring.jpa.properties.hibernate.connection.handling_mode: DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION

I am not creating a PR as this repository seems not maintained anymore, so an issue would be more visible.

@abhishekvats007
Copy link

abhishekvats007 commented Jan 10, 2022

Hi, @alinturbut
Mine is working fine without setting this flag. After a read transaction, the next write is going to correct write db only.

@Override
@Transactional
public UserData saveUser() {
    UserData userData = new UserData();
    userData.setFirstName("Abhishek");
    userData.setName("Abhishek Vats");
    userData.setLastName("Vats");
    return userRepository.save(userData);
}

@Override
@Transactional(readOnly = true)
public UserData getUser(final int id) {
    Optional<UserData> byId = userRepository.findById(id);
    return byId.get();
}

This is simple use case I am testing for read after write. Can you please let me know what use case, I am missing ?

@pmd30011991
Copy link

If you do READ before WRITE, when the Transaction is open, it would acquire a replica connection and use it until the end of outer transaction

@Transaction()
function outer() {
   call getUser()
   call saveUser() <-- error throw here, could not write on read only connection
}

@kanakharaharsh
Copy link

@alinturbut @pmd30011991 I am not using Hibernate. How can I change the Database connection handling mode?

I tried the below approach but it's not working too
https://stackoverflow.com/questions/76136715/transactionsynchronizationmanager-iscurrenttransactionreadonly-always-returnin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants