検討class
- AbstractRoutingDataSource
- IsolationLevelDataSourceRouter
AbstractRoutingDataSource
複数のdatasourceを定義後使用するDatasourceをThreadlocalに保存し、 AbstractRoutingDataSourceのLookupでThreadlocalにあるDatasourceを利用する方式
spring blogの内容サマリ
public class CustomerContextHolder {
private static final ThreadLocal<CustomerType> contextHolder = new ThreadLocal<CustomerType>();
public static void setCustomerType(CustomerType customerType) {
Assert.notNull(customerType, "customerType cannot be null");
contextHolder.set(customerType);
}
public static CustomerType getCustomerType() {
return (CustomerType) contextHolder.get();
}
public static void clearCustomerType() {
contextHolder.remove();
}
}
<bean id="catalog" class="blog.datasource.Catalog">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="blog.datasource.CustomerRoutingDataSource">
<property name="targetDataSources">
<map key-type="blog.datasource.CustomerType">
<entry key="GOLD" value-ref="goldDataSource"/>
<entry key="SILVER" value-ref="silverDataSource"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="bronzeDataSource"/>
</bean>