You will see how to route database connections to the master DB and the slave DBs with Spring's @Transactional(readOnly=true|false)
in this example code.
You can find the basic idea of replication routing datasource in Java (Spring & Non Spring) replication-datasource project.
This is an example for Spring Boot 2 with LazyConnectionDataSourceProxy
+ AbstractRoutingDataSource
.
Refer to the following 3 source codes.
- ReplicationRoutingDataSource.java : routing implementation of
AbstractRoutingDataSource
- ReplicationDataSourceConfig : Core configuration example.
@Primary
and@DependsOn
are required for Spring Boot.
- BoorReplicationDatasourceApplication : Run this boot application, you will see the replicated query results.
Run the following shell command.
./gradlew bootRun
then, you will see the results like the following
# with @Transactional(readOnly = true) method
▶ INFO ### findByIdRead : read_1
# with @Transactional(readOnly = false) method
▶ INFO ### findByIdWrite : write_1