Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RDS reader writer 적용 #701

Merged
merged 5 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions backend/src/main/java/codezap/global/rds/DataSourceConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package codezap.global.rds;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

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.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;

import com.zaxxer.hikari.HikariDataSource;

import lombok.RequiredArgsConstructor;

@Configuration
@RequiredArgsConstructor
@Profile("prod")
@EnableJpaRepositories(basePackages = "codezap")
public class DataSourceConfig {

@Bean
@ConfigurationProperties("spring.datasource.write")
public DataSource writeDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
Comment on lines +29 to +32
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

따로 "spring.datasource.write" 값을 주입하는 코드가 없는데 자동으로 주입이 되는 건가요? 이것도 신기방기하네요

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ㄹㅇㄹㅇ 신기한게 한두개가 아님요

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아마 @ConfigurationProperties를 리플렉션해서 주입해주는 코드가 내부에 있을 것 같네요


@Bean
@ConfigurationProperties("spring.datasource.read")
public DataSource readeDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}

@Bean
@DependsOn({"writeDataSource", "readeDataSource"})
public DataSource routeDataSource() {
DataSourceRouter dataSourceRouter = new DataSourceRouter();
DataSource writerDataSource = writeDataSource();
DataSource readerDataSource = readeDataSource();

Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("write", writerDataSource);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
dataSourceMap.put("write", writerDataSource);
dataSourceMap.put(DataSourceRouter.WRITER_LOOKUP_KEY, writerDataSource);

위의 키들은 DataSourceRouter 의 반환값과 맞춰 주어야 하는건가요??
그렇다면 오탈자 때문에 오류가 나는 것을 예방하기 위해 상수로 관리하는 것은 어떤가요??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋은데요???!

dataSourceMap.put("read", readerDataSource);

dataSourceRouter.setTargetDataSources(dataSourceMap);
dataSourceRouter.setDefaultTargetDataSource(writerDataSource);

return dataSourceRouter;
}

@Bean
@Primary
@DependsOn({"routeDataSource"})
public DataSource dataSource() {
return new LazyConnectionDataSourceProxy(routeDataSource());
}
}
17 changes: 17 additions & 0 deletions backend/src/main/java/codezap/global/rds/DataSourceRouter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package codezap.global.rds;

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

public class DataSourceRouter extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

새로운 트랜잭션인 경우, TransactionSynchronizationManager 에 새로운 트랜잭션을 등록합니다.

TransactionSynchronizationManager으로부터 지금 실행되는 트랜잭션이 readOnly으로 마킹되어있는지 체크하는가 보군요 신기방기


if(readOnly) {
return "read";
}
return "write";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public class LikesService {
private final MemberRepository memberRepository;
private final LikesRepository likesRepository;

@Transactional
public void like(MemberDto memberDto, long templateId) {
Template template = templateRepository.fetchById(templateId);
Member member = memberRepository.fetchById(memberDto.id());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public Page<Template> findAllBy(
return templateRepository.findAll(new TemplateSpecification(memberId, keyword, categoryId, tagIds), pageable);
}

@Transactional
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

위에 create에도 @transactional 해주세요 ~

public Template update(
Member member,
Long templateId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class ThumbnailService {

private final ThumbnailRepository thumbnailRepository;

@Transactional
public void createThumbnail(Template template, SourceCode thumbnail) {
thumbnailRepository.save(new Thumbnail(template, thumbnail));
}
Expand Down
3 changes: 2 additions & 1 deletion backend/src/main/resources/logger/logback-spring-prod.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
<appender-ref ref="console-appender"/>
</logger>

<root level="WARN">
<root level="INFO">
<appender-ref ref="info-appender"/>
Comment on lines +15 to +16
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 부분은 앞으로도 계속 적용할 정책인가요? 아니면 데모데이 이후 변경될 예정인가요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 설정 파일이 잘 적용되는지 정도만 확인하고 삭제하겠습니다~

<appender-ref ref="warn-appender"/>
<appender-ref ref="error-appender"/>
</root>
Expand Down