对不起,我的英文不好。我写的实施AbstractRoutingDataSource:动态数据源路由
public class DatabaseRoutingDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getDatabaseType();
}
}
我创造了新的类的数据库之间进行切换:
public class DatabaseContextHolder {
private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<DatabaseType>();
public static void setDatabaseType(DatabaseType databaseType) {
contextHolder.set(databaseType);
}
public static DatabaseType getDatabaseType() {
return (DatabaseType) contextHolder.get();
}
public static void clearDatabaseType() {
contextHolder.remove();
}
}
其中数据库类型是:
public enum DatabaseType {
MAIN,
BACKUP
}
在我的beans.xml
:
<bean id="mainDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/jdbc/DBMIDS"/>
</bean>
<bean id="backupDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/jdbc/DBMIDS2"/>
</bean>
<bean id="dataSource" class="DatabaseRoutingDataSource">
<property name="targetDataSources">
<map key-type="DatabaseType">
<entry key="MAIN" value-ref="mainDataSource"/>
<entry key="BACKUP" value-ref="backupDataSource"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="mainDataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<bean id="databaseTarget" class="DatabaseBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="database" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="target" ref="databaseTarget"/>
<property name="proxyInterfaces">
<value>Database</value>
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED,-MyException</prop>
</props>
</property>
</bean>
现在,当我试图改变数据源在我的DAO:
public class DatabaseBean extends JdbcDaoSupport implements Database
public void myMethod() {
DatabaseContextHolder.setDatabaseType(DatabaseType.MAIN);
getJdbcTemplate().execute("INSERT INTO test(test) VALUES('test')");
DatabaseContextHolder.setDatabaseType(DatabaseType.BACKUP);
getJdbcTemplate().execute("INSERT INTO test(test) VALUES('test')");
}
determineCurrentLookupKey()被调用一次,第一次执行时getJdbcTemplate(),和数据源不切换。
这可能与一个AbstractRoutingDataSource有关吗?有同样的问题。 – Vedran