Backgroup: I have a large project with more than 500 nodes need to connection to one Database, so connection count is too high. In order to reduce db connections, I want to reuse one connection for all readonly transactions. So, I need to get the "TransactionSynchronizationManager.isCurrentTransactionReadOnly()" in Datasource.getConnection() method. While, in spring-jdbc-5.2.2, DataSourceTransactionManager.doBegin method, the connection is gotten at line 263, the readonly flag is setted at line 298.
Suggestion: Set the readonly flag before getting connection. e.g. in DataSourceTransactionManager.doBegin method
protected void doBegin(Object transaction, TransactionDefinition definition) { TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; ... Connection newCon = obtainDataSource().getConnection(); ...
Then I will override a Datasource, that, return one shared connection to all readonly transactions.
Comment From: quaff
Is it safe to reuse connection across threads?
Comment From: johnny2002
Is it safe to reuse connection across threads?
for readonly operations, it is.
Comment From: quaff
Is it safe to reuse connection across threads?
for readonly operations, it is.
It depends on driver implementation.
Comment From: johnny2002
Is it safe to reuse connection across threads?
for readonly operations, it is.
It depends on driver implementation.
At least, as I tested, oracle, mysql, pgsql are no problem.
Comment From: johnny2002
further more, no matter share connection is safe or not, let developers can get the readonly property as earlier as possible is a good manner. Developers may use the readonly property for other purpos.
Comment From: johnny2002
Is it safe to reuse connection across threads?
for readonly operations, it is.
It depends on driver implementation.
So, what's the decision? will you adopt the change request?
Comment From: snicoll
The PR has been declined, reopening to reconsider this.
Comment From: jhoeller
This effectively got addressed through #31785 in 6.1.2 where LazyConnectionDataSourceProxy
has dedicated support for a read-only DataSource now. And generally, as per #21415, LazyConnectionDataSourceProxy
is recommended for lazy-determined DataSource routing based on those thread-local settings.