简体   繁体   English

Spring JPA根据请求标头更改数据源

[英]Spring JPA change datasource depending on request header

I developed an application with spring-data-rest. 我用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. 我要做的(为多个客户实现一个后端)是根据自定义请求标头中发送的apikey更改存储库的数据源。

The connection info (url, credentials, database) can be retrieved from an external microservice which manages all the database configurations. 可以从管理所有数据库配置的外部微服务检索连接信息(URL,凭据,数据库)。

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. 这个想法是在启动时检索所有可用的数据库连接,并将它们存储在以apikey作为键并将连接信息作为值的映射中。

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. 根据您的JPA提供者,您需要的是多租户支持。

For Hibernate, there is a nice multi-tenancy API available that plugs in with Spring very nicely for configuring what data source to use. 对于Hibernate,有一个不错的多租户 API可以很好地插入Spring,用于配置要使用的数据源。 MultiTenantConnectionProvider and CurrentTenantIdentifierResolver for some API details. 有关一些API的详细信息,请参见MultiTenantConnectionProviderCurrentTenantIdentifierResolver

I finally found a solution using the AbstractRoutingDataSource. 我终于找到了使用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/ http://fizzylogic.nl/2016/01/24/Make-your-Spring-boot-application-multi-tenant-aware-in-2-steps/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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