I am building a service using Spring WebFlux, R2dbc, and Jasync. As I am considering various databases in the current service, I want to use different ConnectionFactory for each package.
So, I tried to create an AbstractRoutingConnectionFactory implementation and branch it from determineCurrentLookupKey method to a different ConnectionFactory with the package name. Like this.
public class CustomRoutingConnectionFactory extends AbstractRoutingConnectionFactory {
@Override
protected Mono<Object> determineCurrentLookupKey() {
return TransactionSynchronizationManager.forCurrentTransaction()
.map(this::getR2dbcKeyByPackage);
}
private String getR2dbcKeyByPackage(TransactionSynchronizationManager transactionManager) {
if (transactionManager.getCurrentTransactionName()
.contains(SomeR2dbcProperties.BASE_PACKAGE)) {
return SomeR2dbcProperties.KEY;
} else if (transactionManager.getCurrentTransactionName()
.contains(OtherR2dbcProperties.BASE_PACKAGE)) {
return OtherR2dbcProperties.KEY;
}
throw new RuntimeException("not supported package: %s");
}
...
}
I tried to compare the package name with the method name used for Transactional annotation in Transaction attribute (definition).
I didn't know for sure about this, but I thought I could use the information here because I could access the TransactionContext using the TransactionSynchronizationManager.
By the way, there is no information about Transaction like the picture below. The picture below shows the part that I checked after running the method with Transactional annotation.
TransactionDefinition is used in the doBegin method of R2dbcTransactionManager, so is there any way to use it in the determineCurrentLookupKey method?