我正在开发一个使用Spring-Webflux和Spring-data-r2dbc的多租户响应式应用程序,使用r2dbc驱动程序连接到Postgresql数据库。多租户部分是基于模式的:每个租户一个模式。因此,根据上下文(例如已登录的用户),请求将命中数据库的某个模式。
我在研究如何在r2dbc中实现这一点。理想情况下,它应该像Hibernate一样使用MultiTenantConnectionProvider(请参见示例16.3)。
我找到了一些资料并做了一些工作:
我在研究如何在r2dbc中实现这一点。理想情况下,它应该像Hibernate一样使用MultiTenantConnectionProvider(请参见示例16.3)。
我找到了一些资料并做了一些工作:
- Could use AbstractRoutingConnectionFactory as mentioned here. But I'm force to create a ConnectionFactory by tenant/schema. It seems to me that is far from efficient/scalable, I would rather use a connection pool like r2dbc-pool
I looked at PostgresqlConnectionFactory. Interesting thing here is that on
prepareConnection
there's a call onsetSchema(connection)
:private Mono<Void> setSchema(PostgresqlConnection connection) { if (this.configuration.getSchema() == null) { return Mono.empty(); } return connection.createStatement(String.format("SET SCHEMA '%s'", this.configuration.getSchema())) .execute() .then(); }
Otherwise I could try to specify the schema in the request as a table prefix:
String s = "tenant-1"; databaseClient.execute("SELECT * FROM \"" + s + "\".\"city\"") .as(City.class) .fetch() .all()