Spring Data sample for a multi-tenanted app where each tenant has its own Azure Cosmos DB container
.
- The application is a simple CRUD REST web service which creates
User
entries in each tenant, and makes use ofazure-spring-data-cosmos
for Azure Cosmos DB SQL API. - At application startup, all the names of existing containers in the
tenants
database are retrieved and stored intenantList
inTenantStorage
class. This class also contains resources to create Cosmos containers named bytenantId
dynamically. Thetenants
database is created if it does not exist. - The application uses
WebRequestInterceptor
to capture a http request header ofTenantId
. This is used to check if the correspondingUser
container (tenant id) exists intenantList
. If it does not, the container will be created. - CRUD operations are performed in UserController using
cosmosTemplate
which is auto-wired along withtenantStorage
which is used to create and reference Cosmos containers dynamically.
This sample application fetches the value of the tenant from request header (TenantId). In a real-world application, it is up to you how to identify this while keeping your application secure. For example, you may want to fetch the identifier from a cookie, or other header name. The approach of assigning a container (or database) to each tenant may be useful if it is necessary to strictly isolate performance for each tenant. However, you should consider the trade-offs in taking this approach. Review our article on Multitenancy and Azure Cosmos DB for more guidance.
Java Development Kit 8
.- An active Azure account. If you don't have one, you can sign up for a free account. Alternatively, you can use the Azure Cosmos DB Emulator for development and testing. As emulator https certificate is self signed, you need to import its certificate to java trusted cert store, explained here.
- Apache Maven.
- (Optional) SLF4J is a logging facade.
- (Optional) SLF4J binding is used to associate a specific logging framework with SLF4J.
SLF4J is only needed if you plan to use logging, please also download an SLF4J binding which will link the SLF4J API with the logging implementation of your choice. See the SLF4J user manual for more information.
- The app uses environment variables
ACCOUNT_HOST
andACCOUNT_KEY
. Make sure these environment variables exist, and are set to your Azure Cosmos DB accountURI
andPRIMARY KEY
respectively. - git clone https://github.com/Azure-Samples/azure-spring-data-cosmos-tenant-by-container-sample.git
- cd azure-spring-data-cosmos-tenant-by-container-sample
- start the application:
mvn spring-boot:run
- Send a request to the web service from a linux based command line (or you can use postman):
curl -s -d '{"firstName":"Theo","lastName":"van Kraay"}' -H "Content-Type: application/json" -H "TenantId: theo" -X POST http://localhost:8080/users
Please refer to azure spring data cosmos for sql api source code for more information.