Skip to content

Commit

Permalink
[Refactor] - RDS reader, writer 엔드포인트 연결 쓰기 작업, 읽기 작업 분리 검토 (#441)
Browse files Browse the repository at this point in the history
* feat: 프로덕션 프로파일 datasource RDS로 변경

* feat: 프로덕션 datasource routing Configuration 작성

* refactor: 의미 있는 문자열 상수화

* fix: LoginService 트랜잭셔널 검토

* fix: TravelPlanService 트랜잭션 속성 검토

* refactor: 사용하지 않는 애너테이션 제거 개선
  • Loading branch information
Libienz authored Sep 23, 2024
1 parent 0aa14a1 commit bf98d21
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import kr.touroot.member.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
Expand All @@ -37,6 +38,7 @@ private Member signUp(OauthUserInformationResponse userInformation) {
return memberRepository.save(userInformation.toMember());
}

@Transactional(readOnly = true)
public LoginResponse login(LoginRequest request) {
String encryptPassword = passwordEncryptor.encrypt(request.password());
Member member = memberRepository.findByEmailAndPassword(request.email(), encryptPassword)
Expand All @@ -45,6 +47,7 @@ public LoginResponse login(LoginRequest request) {
return LoginResponse.of(member, tokenProvider.createToken(member.getId()));
}

@Transactional(readOnly = true)
public LoginResponse reissueToken(TokenReissueRequest request) {
String memberId = tokenProvider.decodeRefreshToken(request.refreshToken());
Member member = memberRepository.findById(Long.valueOf(memberId))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package kr.touroot.global.config;

import com.zaxxer.hikari.HikariDataSource;
import jakarta.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@Profile("prod")
public class DataSourceConfig {

public static final String WRITER = "writer";
public static final String READER = "reader";

@ConfigurationProperties(prefix = "spring.datasource.writer")
@Bean
public DataSource writerDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}

@ConfigurationProperties(prefix = "spring.datasource.reader")
@Bean
public DataSource readerDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}

@DependsOn({"writerDataSource", "readerDataSource"})
@Bean
public DataSource routingDataSource(
@Qualifier("writerDataSource") DataSource writer,
@Qualifier("readerDataSource") DataSource reader) {
DynamicRoutingDataSource routingDataSource = new DynamicRoutingDataSource();

Map<Object, Object> dataSourceMap = new HashMap<>();

dataSourceMap.put(WRITER, writer);
dataSourceMap.put(READER, reader);

routingDataSource.setTargetDataSources(dataSourceMap);
routingDataSource.setDefaultTargetDataSource(writer);

return routingDataSource;
}

@DependsOn({"routingDataSource"})
@Primary
@Bean
public DataSource dataSource(DataSource routingDataSource) {
return new LazyConnectionDataSourceProxy(routingDataSource);
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
return jpaTransactionManager;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package kr.touroot.global.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
return DataSourceConfig.READER;
}
return DataSourceConfig.WRITER;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ public class MemberService {
private final MemberRepository memberRepository;
private final PasswordEncryptor passwordEncryptor;

@Transactional(readOnly = true)
public Member getById(Long memberId) {
return memberRepository.findById(memberId)
.orElseThrow(() -> new BadRequestException("존재하지 않는 사용자입니다."));
}

@Transactional
public Long createMember(MemberRequest request) {
validateRequest(request);
String encryptedPassword = passwordEncryptor.encrypt(request.password());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,12 @@ private List<PlanPlaceTodoResponse> getPlaceTodos(TravelPlanPlace place) {
.toList();
}

@Transactional(readOnly = true)
public Page<TravelPlan> getAllByAuthor(Member member, Pageable pageable) {
return travelPlanRepository.findAllByAuthor(member, pageable);
}

@Transactional(readOnly = true)
public int calculateTravelPeriod(TravelPlan travelPlan) {
return travelPlanDayRepository.findByPlan(travelPlan)
.size();
Expand Down
14 changes: 10 additions & 4 deletions backend/src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,16 @@ spring:
console:
enabled: false
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: ENC(BLlw5HyZCuuLnw9MN5Ez395f+9INR7KoyWKUArAGc5QuMNJw07P06/1HLSZZ6y8M)
username: ENC(s5TCLskHnyopzJBsWU9Akg==)
password: ENC(MlRZxamsKXaRANlE3dX9T3vrdJhtsoE0r6LvSaKZoSU=)
writer:
jdbc-url: ENC(WmWa9T4FlLD0SWKenUhPZgRaUOEcYFt9tsw5MfpOmGfHF5lFMXiYCGElb3S4NBzWfpIxg3daIlhdEgUJaMv4CjmKPJzt2Mt3f/SPOI8rlMHwSA2IrjFw90mHPWJsGO2WPsAZEOX6TeNVpiIhE4nM2w==)
username: ENC(OD+ZUOLOgfa1s4CpW8wmCA==)
password: ENC(SvYVLaigwGxQjPS1yZKaqs4mDC4jUT2f)
driver-class-name: com.mysql.cj.jdbc.Driver
reader:
jdbc-url: ENC(K1rG1kXZV6c/xdrCt4Q/ANwoRneNZjXTppm65H/cuOjDnGNF8X+80yh7FIAvIbrP74royecVW18xk1O3gJAohEudC486T59hYpNJv2HaTiOJBavO5c9sH6UNbFN0kFYyT1nz9Y2uOkUt71fkW2YQ4A==)
username: ENC(7ap5OS9J40A2EaOxU/Qxyg==)
password: ENC(a79pqVIy4+TknqeGj6qtLumkNltqjcx5)
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: false
properties:
Expand Down

0 comments on commit bf98d21

Please sign in to comment.