看这个吧:http://fedulov.website/2015/10/14/dynamic-datasource-routing-with-spring/
就是两个数据库,结构一样,一个是新数据,一个是历史数据,
界面打钩,就查历史数据,否则查新数据,就这意思。
package website.fedulov.routing.RoutingDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DbContextHolder.getDbType(); } }
public enum DbType { MASTER, REPLICA1, }
public class DbContextHolder {
private static final ThreadLocal<DbType> contextHolder = new ThreadLocal<DbType>();
public static void setDbType(DbType dbType) { if(dbType == null){ throw new NullPointerException(); } contextHolder.set(dbType); }
public static DbType getDbType() { return (DbType) contextHolder.get(); }
public static void clearDbType() { contextHolder.remove(); } }
<bean id="dataSource" class="website.fedulov.routing.RoutingDataSource"> <property name="targetDataSources"> <map key-type="com.sabienzia.routing.DbType"> <entry key="MASTER" value-ref="dataSourceMaster"/> <entry key="REPLICA1" value-ref="dataSourceReplica"/> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceMaster"/> </bean>
<bean id="dataSourceMaster" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="${db.master.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean> <bean id="dataSourceReplica" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="${db.replica.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean>
使用方法:
try{ DbContextHolder.setDbType(DbType.REPLICA1); ... } finally { DbContextHolder.clearDbType(); }
根据参数,切换数据源就行,最后记得清空设置,否则影响。
|