Spring 多数据源动态切换

beans.xml

<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource"
  init-method="init" destroy-method="close">
  <property name="url" value="${jdbc_url2}" />
  <property name="username" value="${jdbc_user2}" />
  <property name="password" value="${jdbc_password2}" />
  <property name="maxActive" value="20" />
  <property name="initialSize" value="1" />
  <property name="maxWait" value="60000" />
  <property name="minIdle" value="1" />
  <property name="timeBetweenEvictionRunsMillis" value="60000" />
  <property name="minEvictableIdleTimeMillis" value="300000" />
  <property name="testWhileIdle" value="true" />
  <property name="testOnBorrow" value="false" />
  <property name="testOnReturn" value="false" />
  <property name="poolPreparedStatements" value="true" />
  <property name="maxPoolPreparedStatementPerConnectionSize"
   value="50" />
  <property name="filters" value="stat,log4j" />
  <property name="proxyFilters" ref="log-filter" />

 </bean>
 <bean id="log-filter" class="com.alibaba.druid.filter.logging.Log4jFilter">
  <property name="resultSetLogEnabled" value="false" />
  <property name="statementExecutableSqlLogEnable" value="true" />
  <property name="statementLoggerName" value="sqlLogger" />
 </bean>
 <!-- ibatis配置 -->
 <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
  <property name="configLocation" value="classpath:ibatis.xml" />
  <property name="dataSource" ref="dataSource" />
 </bean>
 <bean id="dataSource" class="zh.dbcenter.DynamicDataSource">
  <property name="targetDataSources">
   <map key-type="java.lang.String">
    <entry key="dataSource1" value-ref="dataSource1" />
    
    <!--<entry key="dataSource2" value-ref="dataSource2" />  -->
   </map>
  </property>
  <property name="defaultTargetDataSource" ref="dataSource1" />
 </bean>

DynamicDataSource.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
 Logger log = Logger.getLogger("DynamicDataSource");
 private Map<Object, Object> _targetDataSources;
 @Override
 protected Object determineCurrentLookupKey() {
  String dataSourceName = DbContextHolder.getDBType();
  if (dataSourceName == null) {
   dataSourceName = "dataSource";
  } else {
   this.selectDataSource(dataSourceName);
   if (dataSourceName.equals("0"))
    dataSourceName = "dataSource";
  }
  log.debug("--------> use datasource " + dataSourceName);
  return dataSourceName;
 }
 public void setTargetDataSources(Map<Object, Object> targetDataSources) {
  this._targetDataSources = targetDataSources;
  super.setTargetDataSources(this._targetDataSources);
  afterPropertiesSet();
 }
 public void addTargetDataSource(String key, BasicDataSource dataSource) {
  this._targetDataSources.put(key, dataSource);
  this.setTargetDataSources(this._targetDataSources);
 }
 public BasicDataSource createDataSource(String driverClassName, String url,
   String username, String password) {
  BasicDataSource dataSource = new BasicDataSource();
  dataSource.setDriverClassName(driverClassName);
  dataSource.setUrl(url);
  dataSource.setUsername(username);
  dataSource.setPassword(password);
  dataSource.setTestWhileIdle(true);
  dataSource.setInitialSize(1);
  dataSource.setMaxActive(5);
  dataSource.setMaxWait(30000);
  return dataSource;
 }
 
 public BasicDataSource createDataSource(Map<String,String> jdbc) {
  String dcn = jdbc.get("driverClassName");
  if(StringUtils.isBlank(dcn)
    ||StringUtils.isEmpty(dcn)
    ||dcn.equals("null"))
  {
   dcn = "oracle.jdbc.driver.OracleDriver";
  }
  BasicDataSource dataSource = new BasicDataSource();
  dataSource.setDriverClassName(jdbc.get("driverClassName"));
  dataSource.setUrl(jdbc.get("url"));
  dataSource.setUsername(jdbc.get("username"));
  dataSource.setPassword(jdbc.get("password"));
  dataSource.setTestWhileIdle(true);
  dataSource.setInitialSize(1);
  dataSource.setMaxActive(5);
  dataSource.setMaxWait(30000);
  return dataSource;
 }
 /**
  * @param dataSourceName
  * @describe 数据源存在时不做处理,不存在时创建新的数据源链接,并将新数据链接添加至缓存
  */
 public void selectDataSource(String dataSourceName) {
  Object sid = DbContextHolder.getDBType();
  if ("0".equals(dataSourceName)) {
   DbContextHolder.setDBType("0");
   return;
  }
  Object obj = this._targetDataSources.get(dataSourceName);
  if (obj != null && sid.equals(dataSourceName)) {
   DbContextHolder.setDBType(dataSourceName);
   return;
  } else {
   
   this.selectDataSource("0");
   Connection conn = null;
   try {
    conn = this.getConnection();
    System.out.println(conn == null);
    
   } catch (SQLException e) {
    e.printStackTrace();
   }
   
   if(conn != null)
   {
    try {
       Map<String,String> jdbc = new HashMap<String, String>();
       PreparedStatement ps = conn
                      .prepareStatement("SELECT * FROM bas_datasource WHERE DBS_ID = ?");
              ps.setString(1, dataSourceName);
              ResultSet rs = ps.executeQuery();
              if (rs.next()) {
               jdbc.put("DBS_ID", rs.getString("DBS_ID"));
               jdbc.put("driverClassName","oracle.jdbc.driver.OracleDriver");
               jdbc.put("url", rs.getString("URL"));
               jdbc.put("username", rs.getString("USERNAME"));
               jdbc.put("password", rs.getString("PASSWORD"));
              }
              rs.close();
              ps.close();
              
              BasicDataSource dataSource = this.createDataSource(jdbc);
     this.setDataSource(dataSourceName, dataSource);
              
          } catch (SQLException e) {
              log.error(e);
          } finally {
              try {
                  conn.close();
              } catch (SQLException e) {
                  log.error(e);
              }
          }
   } 
  }
 }
 /**
  * @param serverId
  * @param dataSource
  */
 public void setDataSource(String dataSourceName, BasicDataSource dataSource) {
  this.addTargetDataSource(dataSourceName, dataSource);
  DbContextHolder.setDBType(dataSourceName);
 }
}

DBCenter.java

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.dbcp.BasicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import zh.Dao.CampusDao;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:beans.xml"}) 
public class DBCenter { 
 
 @Autowired
 private CampusDao campusDao;
  
 @Test 
 public void testCampusAll() { 
  
  System.out.println("傻逼");
  System.out.println(campusDao.findAll().get(0));
  DbContextHolder.setDBType("dataSource2");
  System.out.println(campusDao.findAll().get(0));
  DbContextHolder.setDBType("dataSource1");
  System.out.println(campusDao.findAll().get(0));
  
 }

你可能感兴趣的:(Spring 多数据源动态切换)