-
Notifications
You must be signed in to change notification settings - Fork 378
Description
I would like to route requests to either the master or slave database based on the readOnly attribute of the @Transactional annotation, similar to how it's done in Spring MVC.
However, in R2DBC, there's no component equivalent to LazyConnectionDataSourceProxy.
Because of this, the transaction is not yet initialized at the time TransactionSynchronizationManager is queried, so we cannot determine whether the transaction is read-only.
Is there a specific reason why a LazyConnectionDataSourceProxy-like mechanism hasn't been defined for R2DBC?
I'd love to hear your thoughts on this.
Thanks for all the great work on the project!
The approach you mentioned in #1261 (comment) doesn't fit our use case.
This is because the same read query could be executed against both the master and the slave, which we > want to avoid.
MVC example
core component: AbstractRoutingDataSource, LazyConnectionDataSourceProxy
@Bean
public DataSource dataSource(
@Qualifier("writableDataSource") DataSource writableDataSource,
@Qualifier("readonlyDataSource") DataSource readonlyDataSource
) {
final ReadWriteRoutingDataSource routingDataSource = new ReadWriteRoutingDataSource();
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put(DataSourceType.WRITABLE, writableDataSource);
dataSourceMap.put(DataSourceType.READONLY, readonlyDataSource);
routingDataSource.setTargetDataSources(dataSourceMap);
routingDataSource.setDefaultTargetDataSource(writableDataSource);
routingDataSource.afterPropertiesSet();
return new LazyConnectionDataSourceProxy(routingDataSource);
}
public class ReadWriteRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? DataSourceType.READONLY
: DataSourceType.WRITABLE;
}
}