简体   繁体   中英

Spring JPA change datasource depending on request header

I developed an application with spring-data-rest. I love it and it works like a charme.

What I want to do (to implement one backend for multiple customers) is to change the datasource of my repository depending on an apikey which is sent in a custom request header.

The connection info (url, credentials, database) can be retrieved from an external microservice which manages all the database configurations.

The idea is to retrieve all available database connections on startup and store them in a map with apikey as key and the connection info as value.

I´m not clear about how I can change the datasource of my repo for each incoming request at runtime.

Any ideas?

Depending on your JPA provider, what you are wanting will be multi-tenancy support.

For Hibernate, there is a nice multi-tenancy API available that plugs in with Spring very nicely for configuring what data source to use. MultiTenantConnectionProvider and CurrentTenantIdentifierResolver for some API details.

I finally found a solution using the AbstractRoutingDataSource. This article saved my day. A really easy to use and to understand solution. http://fizzylogic.nl/2016/01/24/Make-your-Spring-boot-application-multi-tenant-aware-in-2-steps/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM