2

I have a requirement like one API REST endpoint which will be connected to 3 databases. In this API, three service implementations, each service will connect to separate database.

I have to use Spring data JPA to get the data from the database.

I am using AbstractRoutingDataSource to create the datasource during application start up.

I have registered 3 datasource beans using application context and planning to create 3 JPA configs in 3 different packages.

Here, My question is to how to map the datasource to JPA repo depending on the request header.

Example:

This is the configuration value

datasource.environment = dev.db2, dev.postgres, dev.mysql

This list of environments may vary like in UAT, we may have uat1.db2, uat2.postgres. This list is dynamic.

In the above scenario I have registered 3 datasource beans using application context.

If the request header value is "dev" then need to inject the dev datasource into corresponding JPA repo.

Similarly, if header values is "dev-1" then inject the corresponding datasource.

Any inputs will be appreciated.

Muqthar Ali
  • 83
  • 10
  • Please be more conrete. Do you have 3 endpoints such as /api/db1, /api/db2/, /api/db3/ which should query data from different datasources or is it determined by the request header such as "datasource=dev", "datasource=prod", "datasource=uat"? – yezper Aug 26 '22 at 10:06
  • Updated my question.Single end point and database will be determined by request header. – Muqthar Ali Aug 26 '22 at 10:07
  • Well if you already configured your 3 datasources you can simply read the header with Springs `@RequestHeader` annotation and then write a method like `DataSource getDataSourceForHeader(String header)` which returns the DataSource for the respective header. – yezper Aug 26 '22 at 10:18
  • JPA config will be loaded during the application start up so at this time, header value will not be available. In this case, how to load the jpa configurations? – Muqthar Ali Aug 26 '22 at 13:48

1 Answers1

0

Create a datasource for each database you want to connect to, such as explained here Spring Boot configure and use two data sources. Then retrieve the request header from the HTTP request by using the @RequestHeader Spring Web Annotation. Then you can implement a method such as DataSource getDatasourceForHeader(String header) which returns the datasource for the respective HTTP header.

yezper
  • 693
  • 3
  • 12
  • I can get the datasource but how to map this datasource to corresponding JPA config ? JPA config will be initialized during application start up time. – Muqthar Ali Aug 26 '22 at 16:54