사용자 도구

사이트 도구


springframework:abstractroutingdatasource

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
springframework:abstractroutingdatasource [2015/11/03 14:02]
kwon37xi [Shard DataSource 구분자]
springframework:abstractroutingdatasource [2015/12/07 13:26]
kwon37xi [Shard DataSource 구분자]
줄 13: 줄 13:
   * 데이터 소스 구분자는 [[https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html|ThreadLocal]] 등으로 현재 요청 쓰레드에 대한 상태를 유지하고 있어야 한다.<code java>   * 데이터 소스 구분자는 [[https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html|ThreadLocal]] 등으로 현재 요청 쓰레드에 대한 상태를 유지하고 있어야 한다.<code java>
 // ThreadLocal로 데이터 소스 구분자 보관 예제 // ThreadLocal로 데이터 소스 구분자 보관 예제
-// 여기서는 static 메소드로 구현했지만 그 경우 모의 객체 기반 단위 테스트 작성이 어려워진다.+// 다른 예제들에서는 static 메소드로 구현했지만 그 경우 모의 객체 기반 단위 테스트 작성이 어려워진다.
 // Bean 으로 생성할 수 있도록 static을 사용하지 않게 하는 것이 좋아보인다. // Bean 으로 생성할 수 있도록 static을 사용하지 않게 하는 것이 좋아보인다.
 public class CustomerContextHolder { public class CustomerContextHolder {
  
-   private static final ThreadLocal<CustomerType> contextHolder = +   private final ThreadLocal<CustomerType> contextHolder = 
             new ThreadLocal<CustomerType>();             new ThreadLocal<CustomerType>();
   
-   public static void setCustomerType(CustomerType customerType) {+   public void setCustomerType(CustomerType customerType) {
       Assert.notNull(customerType, "customerType cannot be null");       Assert.notNull(customerType, "customerType cannot be null");
       contextHolder.set(customerType);       contextHolder.set(customerType);
    }    }
  
-   public static CustomerType getCustomerType() {+   public CustomerType getCustomerType() {
       return (CustomerType) contextHolder.get();       return (CustomerType) contextHolder.get();
    }    }
  
    // 쓰레드가 종료될 때(특히 웹 애플리케이션의 경우 쓰레드 pool로 공유되기 때문에) 기존 데이터 clear가 필요하다.    // 쓰레드가 종료될 때(특히 웹 애플리케이션의 경우 쓰레드 pool로 공유되기 때문에) 기존 데이터 clear가 필요하다.
-   public static void clearCustomerType() {+   public void clearCustomerType() {
       contextHolder.remove();       contextHolder.remove();
    }    }
줄 36: 줄 36:
 </code> </code>
   * 웹 애플리케이션의 경우 Thread Pool로 쓰레드가 공유되기 때문에, Request 종료 시점에 해당 쓰레드의 컨텍스트를 clear 해주는 filter나 interceptor를 두는 것이 좋다.   * 웹 애플리케이션의 경우 Thread Pool로 쓰레드가 공유되기 때문에, Request 종료 시점에 해당 쓰레드의 컨텍스트를 clear 해주는 filter나 interceptor를 두는 것이 좋다.
 +
 +===== Template/Callback 패턴을 통한 Datasource 지정 =====
 +  * 위의 ''CustomerContextHolder''를 통해 DataSource를 지정하고, 해제하는 것을 처리하지 않아 오류가 발생할 수 있다.
 +  * 이를 위해 Template/Callback 패턴으로 Template 메소드가 DataSource Key를 인자로 받아 자동으로 ''CustomerContextHolder''를 초기화하고, Callback 메소드 실행후 초기화를 해주는 패턴으로 가면 좋다.
  
 ===== 트랜잭션 관련 주의할 점 ===== ===== 트랜잭션 관련 주의할 점 =====
springframework/abstractroutingdatasource.txt · 마지막으로 수정됨: 2015/12/07 13:26 저자 kwon37xi