私はかなり長い間この問題に苦しんでいましたが、なんとかハックすることができました! クライアント用の新しい DB が追加された場合、各クライアントには専用の DB があり、スキーマ設計が同じであるため、ソフトウェアを介してデータベースに即座にアクセスできます。
データ ソースは、必要な DB に接続するために実行時に変更されます。通常、私たちの慣習は、ユーザーのアカウント名がデータベース名である、例えばhttps://serverurl/accountname です
内訳は次のとおりです。
Applicationcontext.xml
<bean id="dataSource" class="com.package.util.TenantRouter">
<property name="targetDataSources">
<map>
<entry key="db" value-ref="db"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="parentDataSource"/>
</bean>
<bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:6432/db?autoReconnect=true"/>
<property name="username" value="DBUSER"/>
<property name="password" value="DBPASS"/>
</bean>
<bean id="db" parent="parentDataSource">
<property name="url" value="jdbc:postgresql://localhost:5432/db?autoReconnect=true"/>
<property name="username" value="DBUSER"/>
<property name="password" value="DBPASS"/>
</bean>
TenantRouter クラスでは、次の 2 つのメソッドは IMPERATIVE です。
@Override
protected Object determineCurrentLookupKey() {
String tenant="defaultdb";
if (UserContextUtil.getUserContext()!=null){
tenant = UserContextUtil.getUserContext().getTenant().toString();
}
return tenant;
}
@Override
protected DataSource determineTargetDataSource() {
//current DB
String db_name = (String) determineCurrentLookupKey();
//System.out.println("THIS DB:"+db_name);
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.postgresql.Driver");
String url="jdbc:postgresql://localhost:5432/"+db_name+"?autoReconnect=true";
//System.out.println("URL:"+url);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
は、クライアントの URL で指定された接続先のUserContextUtil.getUserContext().getTenant().toString()
要求された Db を返します。
そんな頭痛に悩まされている方の参考になれば幸いです。
乾杯!