Caching
Arconia Multitenancy keeps cached application data apart per tenant by scoping cache keys to the current tenant.
| This page is about caching your application data. To cache the tenant lookups made while verifying each request, see Caching Tenant Lookups. |
Tenant-Aware Cache Keys
Arconia Multitenancy provides tenant-aware cache key generation through TenantKeyGenerator, an implementation of Spring’s KeyGenerator, ensuring cache isolation between tenants.
A TenantKeyGenerator is auto-configured as a bean named tenantKeyGenerator. It generates cache keys by combining the current tenant identifier with the method parameters, so the same input for different tenants produces different cache entries. The target object and the method are not part of the key, which is also how Spring’s own SimpleKeyGenerator behaves. Keys are therefore unique only within a given cache name. You can use it with Spring’s @Cacheable annotation:
import org.springframework.cache.annotation.Cacheable;
@Service
class ProductService {
@Cacheable(value = "products", keyGenerator = "tenantKeyGenerator")
Product findProduct(String productId) {
// This result is cached per tenant
return productRepository.findById(productId);
}
}
Key generation requires a tenant context. When no tenant is bound, a TenantNotFoundException is thrown rather than falling back to a tenant-independent key. A shared key would let an entry written outside a tenant context, for example, by a scheduled task, be read later by a request belonging to a tenant.
If a cache holds data that is genuinely the same for every tenant, give it its own cache name and leave it on Spring’s default key generator, or wrap the work in TenantContext.where() so a tenant is bound.
Custom Tenant Key Generator
You can provide your own KeyGenerator bean named tenantKeyGenerator to customize how tenant-aware cache keys are generated. It replaces the auto-configured one, so the @Cacheable annotations referring to tenantKeyGenerator use it without changes:
import org.springframework.cache.interceptor.KeyGenerator;
@Bean
KeyGenerator tenantKeyGenerator() {
return (target, method, params) -> {
// Custom key generation logic
};
}