/spring-tenant

spring-tenant

Primary LanguageJava

spring-tenant

Features

  • Postgresql multi tenant support
  • Oracle multi tenant support

Maven

<dependency>
  <groupId>br.com.zup</groupId>
  <artifactId>spring-tenant</artifactId>
  <version>VERSION</version>
</dependency>

Common properties

Define a prefix for your tenants and add in your spring application.properties:

tenant.prefix=my_prefix

Postgresql

Supported without any special configuration.

Oracle

It's necessary to define the default tenant in your spring application.properties:

tenant.default=some_user

Spring Configuration

This project has dependency to spring-jdbc, and the beans dataSource and jdbcTemplate needs to be provided by your spring application.

@Configuration
@Import(TenantConfig.class) // import tenant configuration
public class YourAppConfig {

  @Bean
  public JdbcTemplate jdbcTemplate(DataSource dataSource) { // it depends on a dataSource
    return new JdbcTemplate(dataSource);
  }
}

Spring Boot Profile

Set the database profile via java args:

postgresql:

-Dspring.profiles.active=postgresql

oracle:

-Dspring.profiles.active=oracle

Tenant Discoverer

Snippet code to get all tenants by a particular prefix

 @Value("${tenant.prefix}")
 private String tenantPrefix;
 
 @Autowired
 private TenantDiscoverer tenantDiscoverer;
    
 Optional<List<Tenant>> tenants = tenantDiscoverer.getTenants(tenantPrefix);

Tenant Prepare Connection

The main component of solution, it's responsible for intercept all connections from javax.sql.DataSource.getConnection and execute the alter session based from tenant in your context (thread local). By default this component is already configured.

Set tenant in your current context

  String tenant = getTenant();// get tenant from request (e.g. Header) or database (e.g. TenantDiscoverer)
  TenantContextHolder.set(tenant);
  // run some code to access your database...
  // all database operations are run in your tenant session also prepared by component TenantConnectionPrepareAspect.

Next features

  • Support more database (e.g. MySQL, SQLServer, DB2, Sybase, Firebird, etc)