Spring MVC 동적 전환 데이터베이스

12949 단어 Spring
프로젝트 에서 데이터 베 이 스 를 동적 으로 전환 해 야 하 는 수 요 를 만 났 습 니 다. 특정한 인터페이스 에서 다른 데이터베이스 에 가서 정 보 를 조회 하고 코드 1 을 직접 올 려 야 합 니 다. 새 DataSourceType. 자바 (데이터베이스 이름 설정)
package com.grand.datasourse;
/**
 *       -             
 * @author 
 *
 * @time 2017 10 23 
 */
public class DataSourceType {

    public static final String SOURCE_UWP = "uwp_dbsourse";//    
    public static final String SOURCE_WD = "wd_dbsourse";//    

}

2. 새 DataSourceContextHolder. java 데이터베이스 클래스 전환
package com.grand.datasourse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * @author           :     
 * 
 * @time 2017 10 22 
 */
public class DataSourceContextHolder {
    //      
    private static final ThreadLocal contextHolder = new ThreadLocal();
    private static final Logger LOG = LoggerFactory
            .getLogger(DataSourceContextHolder.class);
    /**
     *    AOP               
     *      
     * @param dbType     -       
     */
    public static void setDbType(String dbType) {
        try {
            contextHolder.set(dbType);
        } catch (Exception e) {
            // TODO: handle exception
            LOG.debug("ERROR____DB_Exception");
            LOG.debug(e.getMessage());
        }

    }

    /**
     *    AbstractRoutingDataSource    ,  key     
     * @return java.lang.String
     */
    public static String getDbType() {
        String dataSourse  =  contextHolder.get();

        if(null == dataSourse){

            DataSourceContextHolder.setDbType(DataSourceType.SOURCE_UWP);
        }

        return  contextHolder.get();
    }

    /**
     *         
     */
    public static void clearDbType() {
        contextHolder.remove();
    }
}

3. 새 DynamicDataSource. java 데이터 원본 설정
package com.grand.datasourse;

import java.util.logging.Logger;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * descrption:        
 * @author 
 *  AbstractRoutingDataSource      determineCurrentLookupKey       route   
 *               .       
 * @time 2017 10 22 
 */
public class DynamicDataSource extends AbstractRoutingDataSource{

    @Override  
    public Logger getParentLogger() {  
           return null;  
    }  

    @Override  
    protected Object determineCurrentLookupKey() {  
           return DataSourceContextHolder.getDbType();//       
    } 

}

4. applicationContext. xml 에 데이터 원본 설정

"uwp_dbsourse" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
          "driverClass" value="${jdbc.driverClassName2}" />
        "jdbcUrl" value="${jdbc.url2}" />
        "user" value="${jdbc.userDS.username2}" />
        "password" value="${jdbc.userDS.password2}" />
        
        "minPoolSize" value="1" />
        
        "maxPoolSize" value="200" />
        
        "maxIdleTime" value="1800" />
        
        "acquireIncrement" value="5" />
        
        "maxStatements" value="1000" />
        
        "idleConnectionTestPeriod" value="60" />
        
        "acquireRetryAttempts" value="30" />
        "breakAfterAcquireFailure" value="true" />
        "testConnectionOnCheckout" value="false" />
    
    
   "wd_dbsourse" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
          "driverClass" value="${jdbc.driverClassName1}" />
        "jdbcUrl" value="${jdbc.url1}" />
        "user" value="${jdbc.userDS.username1}" />
        "password" value="${jdbc.userDS.password1}" />
        
        "minPoolSize" value="1" />
        
        "maxPoolSize" value="200" />
        
        "maxIdleTime" value="1800" />
        
        "acquireIncrement" value="5" />
        
        "maxStatements" value="1000" />
        
        "idleConnectionTestPeriod" value="60" />
        
        "acquireRetryAttempts" value="30" />
        "breakAfterAcquireFailure" value="true" />
        "testConnectionOnCheckout" value="false" />
    

      
   "dataSource" class= "com.grand.datasourse.DynamicDataSource" >  
          "targetDataSources">  
                "java.lang.String">  
                      "wd_dbsourse" key= "wd_dbsourse">  
                      "uwp_dbsourse" key= "uwp_dbsourse">  
                  
            
          "defaultTargetDataSource" ref= "uwp_dbsourse">        
    

5. 서비스 계층 호출
public List getTest(){

        List list = null;
        try {
            //      
            DataSourceContextHolder.setDbType(DataSourceType.SOURCE_WD);




            list = wdFundMapper.getTest();

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error(e.getMessage());
        }
        DataSourceContextHolder.clearDbType();//    
        return list;
    }

주의: 프로젝트 에서 이러한 service 층 호출 방식 은 작은 하 자가 존재 합 니 다. 같은 service 에서 하나의 라 이브 러 리 만 호출 할 수 있 고 라 이브 러 리 를 자 르 는 작업 을 할 수 없습니다. 예 를 들 어 A service 에서 메 인 라 이브 러 리 B service 를 호출 할 때 라 이브 러 리 A 에서 B 를 호출 하 는 방법 을 사용 하지 않 으 면 본인 의 방법 은 라 이브 러 리 에서 호출 하 는 방법 을 B 에 통일 적 으로 쓰 는 것 입 니 다.제어 층 에서 AB 방법 을 동시에 호출 하여 데 이 터 를 제어 층 에서 구분 합 니 다.

좋은 웹페이지 즐겨찾기