반응형
이번엔 flyway를 다중 데이터베이스 커넥션 환경에 적용해보자
AbstractRoutingDataSource 를 사용하여 DataSource를 유동적으로 변경할 수 있는 환경을 만들었다.
@Slf4j
public class TenantRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
log.info(">>> determineCurrentLookupKey thread: {},{}",Thread.currentThread().getId(), Thread.currentThread().getName() );
log.info(">>> RoutingDataSource: {}", ThreadTenantStorage.getTenantId());
return ThreadTenantStorage.getTenantId();
}
}
기준 값은 ThreadLocal 을 사용하여 각 쓰레드 별로 설정한다.
public class ThreadTenantStorage {
private static ThreadLocal<DataSourceType> currentTenant = new ThreadLocal<>();
public static void setTenantId(DataSourceType dataSourceType) {
currentTenant.set(dataSourceType);
}
public static DataSourceType getTenantId() {
return currentTenant.get();
}
public static void clear() {
currentTenant.remove();
}
}
중요한 부분은 아래와 같은데 위에서 설정한 DataSource를 순회하면서 Flyway를 통해 마이그레이션 해주면 된다.
public void migrate() {
dataSourceProperties
.getDataSources()
.values()
.stream()
.map(dataSourceObj -> (DataSource) dataSourceObj)
.forEach(this::migrate);
}
private void migrate(DataSource dataSource) {
Flyway flyway = Flyway.configure().dataSource(dataSource).load();
flyway.migrate();
}
https://github.com/zeroest/zeroest-base_frame/commit/c7b67b7902efee8b79b106004c91bb4ca9690b27
Apply multi database flyway · zeroest/zeroest-base_frame@c7b67b7
inspired by https://github.com/arkuksin/flyway-multitenancy
github.com
반응형
'Spring' 카테고리의 다른 글
Spring - flyway (0) | 2021.08.18 |
---|---|
QueryDsl with Lombok (0) | 2021.08.05 |
Zipkin - Docker MySQL (0) | 2021.07.25 |
Spring boot 2.5 이상 docker를 위한 unpack (0) | 2021.07.17 |
Mapstruct & Lombok 적용 (3) | 2021.04.16 |