最近因?yàn)轫?xiàng)目需要在做兩個項(xiàng)目間數(shù)據(jù)同步的需求,具體是項(xiàng)目1的數(shù)據(jù)通過消息隊(duì)列同步到項(xiàng)目2中,因?yàn)檫@個更新操作還涉及到更新多個庫的數(shù)據(jù),所以就需要多數(shù)據(jù)源切換的操作。下面就講講在Spring中如何進(jìn)行數(shù)據(jù)源切換。這里是使用AbstractRoutingDataSource類來完成具體的操作,AbstractRoutingDataSource是Spring2.0后增加的。
實(shí)現(xiàn)數(shù)據(jù)源切換的功能就是自定義一個類擴(kuò)展AbstractRoutingDataSource抽象類,其實(shí)該相當(dāng)于數(shù)據(jù)源DataSourcer的路由中介,可以實(shí)現(xiàn)在項(xiàng)目運(yùn)行時根據(jù)相應(yīng)key值切換到對應(yīng)的數(shù)據(jù)源DataSource上。先看看AbstractRoutingDataSource的源碼:
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean { /* 只列出部分代碼 */ private Map<Object, Object> targetDataSources; private Object defaultTargetDataSource; private boolean lenientFallback = true; private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); private Map<Object, DataSource> resolvedDataSources; private DataSource resolvedDefaultDataSource; @Override public Connection getConnection() throws SQLException { &n