双数据源切换问题

  首先当然是建立在需要用到两个数据库的情况下,配置的xml文件中重要部分

  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver">  
        </property>  
        <property name="url" value="jdbc:sqlserver://192.168.0.1:1433; DatabaseName=A">  
        </property>  
        <property name="username" value="sa"></property>  
        <property name="password" value="123456"></property>  
  </bean>  
  <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver">  
        </property>  
        <property name="url" value="jdbc:sqlserver://192.168.0.2:1433;databaseName=B">  
        </property>  
        <property name="username" value="sa"></property>  
        <property name="password" value="123456"></property>  
   </bean>
   <bean id="dynamicDataSource" class="com.key.util.DynamicDataSource" >  
        <property name="targetDataSources">  
            <map key-type="java.lang.String">  
                <entry value-ref="dataSource" key="dataSource"></entry>  
                <entry value-ref="dataSource2" key="dataSource2"></entry>  
            </map>  
        </property>  
        <property name="defaultTargetDataSource" ref="dataSource" >  
        </property>  
   </bean> 
dataSourcedataSource2 是我在项目中用到的不同数据源,id为dynamicDataSource配置的默认数据源
//需要用到的类
public
class CustomerContextHolder { public static final String DATA_SOURCE_A = "dataSource"; public static final String DATA_SOURCE_B = "dataSource2"; private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setCustomerType(String customerType) { contextHolder.set(customerType); //各个线程中访问的是不同的对象 } public static String getCustomerType() { return contextHolder.get(); } public static void clearCustomerType() { contextHolder.remove(); } }

关于ThreadLocal的部分源码如下

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
/** * Get the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @return the map */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; } /** * Create the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @param firstValue value for the initial entry of the map */ void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
        /**
         * Set the value associated with key.
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {
            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();
                if (k == key) {
                    e.value = value;
                    return;
                }
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }
            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
 

使用方法具体如下


    public String getList(){
        CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_B);//切换到B数据源
        TestService ccsqService=SpringUtil.getApplicationContext().getBean(TestService.class);
        List<Ccsq> list=ccsqService.getCcsqList();
        CustomerContextHolder.clearCustomerType();//清除,回到默认数据源
        result = JSONArray.fromObject(list);
        return SUCCESS;
    }

到此为止了,这就是双数据源切换使用的大概了~

原文地址:https://www.cnblogs.com/whiteme/p/7575457.html