I have multitenant Spring Boot application with REST endpoints. Currently I have implemented AbstractDataSource interface for mutlitenant configuration based on tenant-id from request header.
public class TenantAwareRoutingDataSource extends AbstractDataSource {
private final Map<Object, DataSource> resolvedDataSources = new ConcurrentHashMap<>();
@Override
public Connection getConnection() throws SQLException {
return this.determineTargetDataSource().getConnection();
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return this.determineTargetDataSource().getConnection(username, password);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return iface.isInstance(this) ? (T) this : this.determineTargetDataSource().unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this) || this.determineTargetDataSource().isWrapperFor(iface);
}
protected Object determineCurrentLookupKey() {
return RequestInfoThreadLocal.getTenantId();
}
protected DataSource determineTargetDataSource() {
Object lookupKey = this.determineCurrentLookupKey();
DataSource dataSource =
Optional.ofNullable(this.resolvedDataSources.get(lookupKey))
.orElse(this.resolvedDataSources.values().iterator().next());
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
} else {
return dataSource;
}
}
public void addDataSource(String tenantId, DataSource dataSource) {
resolvedDataSources.putIfAbsent(tenantId, dataSource);
}
}
I would like to implement WebSocket service for data synchronization. I must use multitenancy for connection (based on tenant for user). What is the best pattern and solution?