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

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

问题描述

到目前为止,我知道设置数据库名称(与Spring Data ArangoDB一起使用)的唯一方法是,在扩展AbstractArangoConfiguration的同时,在database()方法中对其进行硬编码,如下所示:

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()方法@Override以返回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);

    }
}

然后可以在代码中的任何位置(例如,在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.

P.s.通过阅读通过)和

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天全站免登陆