Skip to content

Commit

Permalink
refactor: DataSourceType enum 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
mcodnjs committed Oct 19, 2023
1 parent a4b713c commit daf8d5e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package hanglog.global.config.datasource;

import static hanglog.global.config.datasource.DataSourceType.REPLICA;
import static hanglog.global.config.datasource.DataSourceType.SOURCE;

import java.util.HashMap;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
Expand Down Expand Up @@ -40,8 +43,8 @@ public DataSource routingDataSource(
final RoutingDataSource routingDataSource = new RoutingDataSource();

final HashMap<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("source", sourceDataSource);
dataSourceMap.put("replica", replicaDataSource);
dataSourceMap.put(SOURCE, sourceDataSource);
dataSourceMap.put(REPLICA, replicaDataSource);

routingDataSource.setTargetDataSources(dataSourceMap);
routingDataSource.setDefaultTargetDataSource(sourceDataSource);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package hanglog.global.config.datasource;

public enum DataSourceType {

SOURCE, REPLICA
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
package hanglog.global.config.datasource;

import static hanglog.global.config.datasource.DataSourceType.REPLICA;
import static hanglog.global.config.datasource.DataSourceType.SOURCE;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Slf4j
public class RoutingDataSource extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
final String currentTransactionName = TransactionSynchronizationManager.getCurrentTransactionName();
final boolean isReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
logger.info(currentTransactionName + " Transaction Read Only가 " + isReadOnly + " 입니다.");

if (isReadOnly) {
logger.info("Replica 서버로 요청합니다.");
return "replica";
log.info(currentTransactionName + " Transaction:" + "Replica 서버로 요청합니다.");
return REPLICA;
}

logger.info("Source 서버로 요청합니다.");
return "source";
log.info(currentTransactionName + " Transaction:" + "Source 서버로 요청합니다.");
return SOURCE;
}
}

0 comments on commit daf8d5e

Please sign in to comment.