java / expert
Snippet
Dynamic Database Routing with AbstractRoutingDataSource
AbstractRoutingDataSource allows for switching between multiple physical DataSources at runtime based on a lookup key, typically stored in a ThreadLocal context. This is essential for multi-tenant architectures where each customer has their own database.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class TenantRoutingDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return TenantContext.getCurrentTenant();}}@Configurationpublic class DataSourceConfig {@Beanpublic DataSource dataSource() {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("TENANT_A", dataSourceA());targetDataSources.put("TENANT_B", dataSourceB());TenantRoutingDataSource routingDataSource = new TenantRoutingDataSource();routingDataSource.setTargetDataSources(targetDataSources);routingDataSource.setDefaultTargetDataSource(dataSourceA());return routingDataSource;}}
spring
Breakdown
1
protected Object determineCurrentLookupKey()
Determines the key used to look up the actual DataSource for the current thread.
2
routingDataSource.setTargetDataSources(targetDataSources)
Registers the map of available DataSources linked to their respective keys.