Spring Boot 2 With Multiple Datasources
In this article, see how your Spring Boot application can interact with multiple datasources.
Join the DZone community and get the full member experience.Join For Free
In this article, I’m going to explain how your Spring Boot application can interact with multiple datasources and not necessarily the same type (Postgres for this demo), but it can be applied across the other relational databases. There are cases that you need to have multiple datasources from different vendors, but the general concept is similar, and this example can be useful with a few changes in the project configuration (application.yml).
For this demo, I chose PostgresSQL Data Replication, which is common in a high load database with high traffic in the application.
There are times that even having the best database (PostgresSQL, Oracle, MySQL, .. ) Tuning can not be as help-full as much as When you separate Read DB and Writes DB in Application Level.
For this demo, you need two separate Postgres databases where one is the master and the other one is the replica.
I have used two PostgresSQL databases, which are running on my local Docker on two separate ports: 5432 and 5433.
You might also want to read: Set up Multiple DataSources With Spring Boot and Spring Data in PCF
For simplicity, just run:
docker-compose up --force-recreate.
docker-compose.yml is already in the project, which contains two PostgresSQL databases in two different ports, with
Note: You can always uninstall it as:
docker-compose down if you need to.
From https://start.spring.io/, select web, data-jpa, lombok, postgresDriver.
For this demo, I used HikariDataSource as a default connection pool library by Spring Boot 2.2.2.
We need to have two separate datasources and EntityManagers, one for the writes (Master/Primary) and one for Reads (Slave/Secondary).
Since both DataSourceConfigWrite and DataSourceConfigRead are taking their configs from: “spring.datasource-write” and “spring.datasource-read”, the entityManagerFactory for each datasource can not get JPA configurations from application.yml . Thats why JPA configurations are added later on from static Property “JPA_PROPERTIES”. You can also add independent @ConfigurationProperties(“spring.jpa”) to supply your JPA configs based on your spring profile.
As you can see, I have two datasources as datasource-write and datasource-read with their own credentials.
DataSource configurations for WriteDB:
DataSource Configurations for ReadDB:
Read and Write repositories should be in a separated package:
You also need to set:
And the actual logics are in the service layer:
I have added the project source code in GitHub.
Opinions expressed by DZone contributors are their own.