Multi-tenancy with a separate database per customer, using Spring Data ArangoDB

风格不统一 提交于 2019-12-11 12:12:41

问题


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?

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

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


回答1:


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()}";
    }

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);

    }
}

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. I became aware of this possibility by reading the ArangoTemplate code and a Spring Expression support documentation section (via), and one merged pull request.



来源:https://stackoverflow.com/questions/56432395/multi-tenancy-with-a-separate-database-per-customer-using-spring-data-arangodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!