使用 Spring Data ArangoDB 为每个客户提供一个单独的数据库的多租户 [英] Multi-tenancy with a separate database per customer, using Spring Data ArangoDB

查看:36
本文介绍了使用 Spring Data ArangoDB 为每个客户提供一个单独的数据库的多租户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我知道设置数据库名称以与 Spring Data ArangoDB 一起使用的唯一方法是将其硬编码在 database() 方法中,同时扩展 AbstractArangoConfiguration,像这样:

So far, the only way I know to set the name of a database, to use with Spring Data ArangoDB, is by hardcoding it in a database() method while extending AbstractArangoConfiguration, like so:

@Configuration
@EnableArangoRepositories(basePackages = { "com.company.mypackage" })
public class MyConfiguration extends AbstractArangoConfiguration {

  @Override
  public ArangoDB.Builder arango() {
    return new ArangoDB.Builder();
  }

  @Override
  public String database() {
    // Name of the database to be used
    return "example-database";
  }

}

如果我想实现多租户怎么办,其中每个租户在单独的数据库中都有数据并使用例如一个子域来确定应该使用哪个数据库名称?

What if I'd like to implement multi-tenancy, where each tenant has data in a separate database and use e.g. a subdomain to determine which database name should be used?

Spring Data ArangoDB 使用的数据库能否在运行时动态确定?

Can the database used by Spring Data ArangoDB be determined at runtime, dynamically?

此问题与此处的讨论有关:管理多租户 ArangoDB 连接- 但特定于 Spring Data ArangoDB.

This question is related to the discussion here: Manage multi-tenancy ArangoDB connection - but is Spring Data ArangoDB specific.

推荐答案

事实证明这非常简单:只需更改 ArangoConfiguration database() 方法 @覆盖以返回一个Spring表达式(SpEL):

Turns out this is delightfully simple: Just change the ArangoConfiguration database() method @Override to return a Spring Expression (SpEL):

    @Override
    public String database() {
        return "#{tenantProvider.getDatabaseName()}";
    }

在这个例子中引用了一个 TenantProvider @Component ,它可以像这样实现:

which in this example references a TenantProvider @Component which can be implemented like so:

@Component
public class TenantProvider {

    private final ThreadLocal<String> databaseName;

    public TenantProvider() {
        super();
        databaseName = new ThreadLocal<>();
    }

    public String getDatabaseName() {
        return databaseName.get();
    }

    public void setDatabaseName(final String databaseName) {
        this.databaseName.set(databaseName);

    }
}

此组件可以在代码中的任何位置 @Autowired 以设置数据库名称,例如在 servlet 过滤器中,或者在我的情况下在 Apache Camel 路由处理器和数据库服务方法中.

This component can then be @Autowired wherever in your code to set the database name, such as in a servlet filter, or in my case in an Apache Camel route Processor and in database service methods.

附言我通过阅读 ArangoTemplate 代码和 Spring 表达式支持文档部分(via)和一个合并的拉取请求.

P.s. I became aware of this possibility by reading the ArangoTemplate code and a Spring Expression support documentation section (via), and one merged pull request.

这篇关于使用 Spring Data ArangoDB 为每个客户提供一个单独的数据库的多租户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆