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

[FEAT] master api 서버 모듈 #100

Merged
merged 23 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2645e29
Merge branch 'develop' of https://github.com/JNU-econovation/Whoz-in-…
inferior3x Dec 18, 2024
12767a3
update: NetworkConfig - @Value 기본값 삭제
inferior3x Dec 19, 2024
f9bffbc
update(main-api): domain모듈 compileOnly -> implementation
inferior3x Dec 19, 2024
f4be8ec
rename: NetworkLog -> NetworkApi
inferior3x Dec 20, 2024
42c3edc
chore(domain-jpa): yml 필요없는 주석 제거 및 환경변수명 수정
inferior3x Dec 20, 2024
6d05af6
feat: master-api 모듈 추가
inferior3x Dec 20, 2024
8bd6c0a
chore: logback-spring.xml 이동
inferior3x Dec 20, 2024
5f1d81a
chore(master-api): yml 분리
inferior3x Dec 20, 2024
798c455
chore(main-api): logback-common.xml 추가
inferior3x Dec 20, 2024
565f6c6
chore(master-api): logback-command.xml 제거
inferior3x Dec 20, 2024
1294c9f
chore(network-api): logback-common.xml 추가
inferior3x Dec 20, 2024
3fbf1ad
feat(domain-jpa): datasource 따로 설정
inferior3x Dec 21, 2024
d70dbb5
fix: 다른 database의 datasource, jpa 관련 빈을 등록할 수 있도록 Primary로 변경
inferior3x Dec 21, 2024
c214a53
update(domain-jpa): 히카리 풀 이름 설정
inferior3x Dec 21, 2024
4c8d60f
fix: AOP를 위해 DAO 클래스 final 제거
inferior3x Dec 21, 2024
99fa9f3
update(domain-jpa): TransactionManager @Primary 제거
inferior3x Dec 21, 2024
23e1c14
feat(log-writer): datasource 따로 설정
inferior3x Dec 21, 2024
0973a07
depend(main-api): spring transaction 의존성 추가
inferior3x Dec 22, 2024
86e3d40
fix(main-api): AOP 사용할 수 있도록 final 제거
inferior3x Dec 22, 2024
c59b233
fix: AOP가 적용된 Handler 프록시 객체를 가져오도록 변경
inferior3x Dec 22, 2024
999fb00
chore: spring 모듈 제거
inferior3x Dec 22, 2024
3e2c01c
update: @PropertySource 대신 spring.config.import 사용
inferior3x Dec 22, 2024
99051dc
test(log-writer): log-writer에서 사용하는 @Transactional은 log-writer의 trans…
inferior3x Dec 23, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.whoz_in.domain_jpa.config;

import com.zaxxer.hikari.HikariDataSource;
import jakarta.persistence.EntityManagerFactory;
import java.util.Map;
import javax.sql.DataSource;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(
basePackages = "com.whoz_in.domain_jpa",
entityManagerFactoryRef = "domainJpaEntityManagerFactory",
transactionManagerRef = "domainJpaTM"
)
@RequiredArgsConstructor
public class DataSourceConfig {
//DB 연결 세팅값 객체
//잠깐쓸거라 밖으로 빼지 않았음
//설정마다 필드가 다를 수 있으므로 공통 모듈로 빼지 않았음
@Getter
@Setter
public static class DataSourceProperties {
private String url;
private String username;
private String password;
private String driverClassName;
}
//하이버네이트 관련 설정값 객체
@Getter
@Setter
public static class HibernateProperties {
private String ddlAuto;
private boolean formatSql;
private boolean showSql;
}

//세팅값 객체를 빈으로 등록함
//@Bean 메서드를 통해 자동으로 빈 등록이 되기 때문에 @ConfigurationPropertiesScan 없이도 동작함
@Bean
@ConfigurationProperties("domain-jpa.datasource")
public DataSourceProperties domainJpaDataSourceProperties(){
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("domain-jpa.hibernate")
public HibernateProperties domainJpaHibernateProperties(){
return new HibernateProperties();
}

//세팅값을 통해 DataSource 생성
@Primary
@Bean
public DataSource domainJpaDataSource(DataSourceProperties properties) {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setPoolName("DomainJpaHikariPool");
dataSource.setJdbcUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
dataSource.setDriverClassName(properties.getDriverClassName());
return dataSource;
}

//JPA 설정
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean domainJpaEntityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("domainJpaDataSource") DataSource dataSource,
@Qualifier("domainJpaHibernateProperties") HibernateProperties hibernateProperties) {
return builder
.dataSource(dataSource) //DataSource 지정
.persistenceUnit("domain_jpa") //이름
.packages("com.whoz_in.domain_jpa") //JPA 엔티티가 존재하는 패키지
.properties(
Map.of(
"hibernate.hbm2ddl.auto", hibernateProperties.ddlAuto,
"hibernate.show_sql", hibernateProperties.showSql,
"hibernate.format_sql", hibernateProperties.formatSql
)
)
.build();
}

@Primary
@Bean("domainJpaTM")
public PlatformTransactionManager domainJpaTransactionManager(
@Qualifier("domainJpaEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
//필요하면 설정 추가하기
return new JpaTransactionManager(entityManagerFactory);
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
package com.whoz_in.domain_jpa.config;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;


@Configuration
@EnableJpaAuditing
//기본적으로 SpringApplication 모듈에서 찾기 때문에 이 모듈에서도 찾을 수 있도록 함
@EnableJpaRepositories(basePackages = {"com.whoz_in.domain_jpa"})
@EntityScan(basePackages = "com.whoz_in")
public class JpaConfig {
}
public class JpaConfig {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
domain-jpa:
hibernate:
ddl-auto: create
show_sql: true
format_sql: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
spring:
jpa:
open-in-view: false

domain-jpa:
datasource:
url: ${DB_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
driver-class-name: ${DB_DRIVER_CLASS}
hibernate:
ddl-auto: validate
show_sql: false

logging:
level:
root: info

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.whoz_in.log_writer.config;

import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration("logWriterDataSourceConfig")
@RequiredArgsConstructor
public class DataSourceConfig {
public static final String LOG_WRITER_TRANSACTION_MANAGER = "logWriterTransactionManager";
@Getter
@Setter
public static class DataSourceProperties {
private String url;
private String username;
private String password;
private String driverClassName;
}

@Bean
@ConfigurationProperties("log-writer.datasource")
public DataSourceProperties logWriterDataSourceProperties() {
return new DataSourceProperties();
}

@Bean
public DataSource logWriterDataSource(DataSourceProperties properties) {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setPoolName("LogWriterHikariPool");
dataSource.setJdbcUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
dataSource.setDriverClassName(properties.getDriverClassName());
return dataSource;
}

@Bean
public JdbcTemplate logWriterJdbcTemplate(@Qualifier("logWriterDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}

// 트랜잭션 매니저 - 아직은 쓸모 없는거 같아서 등록 안했음
@Bean(LOG_WRITER_TRANSACTION_MANAGER)
public PlatformTransactionManager logWriterTransactionManager(@Qualifier("logWriterDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

//실행시킬 프로세스들이 필요로 하는 정보를 제공하는 역할을 한다.
//이를 위해 network-<profile>.json에서 설정값을 가져온다.
//설정된 값들이
//local 혹은 prod만 지원한다.
@Getter
@Component
public class NetworkConfig {
Expand All @@ -25,7 +25,7 @@ public class NetworkConfig {
private final List<ManagedInfo> arpList;

@SuppressWarnings("unchecked")
public NetworkConfig(@Value("${spring.profiles.active:default}") String profile, ResourceLoader loader, ObjectMapper mapper) {
public NetworkConfig(@Value("${spring.profiles.active}") String profile, ResourceLoader loader, ObjectMapper mapper) {
String jsonPath = "classpath:/network-%s.json".formatted(profile);
Resource resource = loader.getResource(jsonPath);
Map<String, Object> map;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
@Slf4j
@Component
@RequiredArgsConstructor
public final class ManagedLogDAO {
public class ManagedLogDAO {

private final JdbcTemplate jdbcTemplate;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
spring:
config:
import:
- "classpath:env-log-writer.properties"

log-writer:
datasource:
url: ${DB_URL}
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
driver-class-name: ${DB_DRIVER_CLASS}

sudo_password: ${SUDO_PASSWORD}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.whoz_in.log_writer.archtect;

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods;
import static com.whoz_in.log_writer.config.DataSourceConfig.LOG_WRITER_TRANSACTION_MANAGER;

import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.domain.JavaMethod;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ArchRule;
import com.tngtech.archunit.lang.ConditionEvents;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.annotation.Transactional;


class LogWriterTransactionManagerTest {

//@Transactional를 사용할 때 transactionManager를 DataSourceConfig.LOG_WRITER_TRANSACTION_MANAGER로 명시해야 한다
@Test
void Transactional_어노테이션은_logWriterTransactionManager를_사용해야합니다() {
JavaClasses importedClasses = new ClassFileImporter().importPackages("com.whoz_in.log_writer");
ArchRule rule = methods()
.that().areAnnotatedWith(Transactional.class)
.should(validateTransactionManager())
.allowEmptyShould(true);

rule.check(importedClasses);
}

private static ArchCondition<JavaMethod> validateTransactionManager() {
return new ArchCondition<>("use logWriterTransactionManager") {
@Override
public void check(JavaMethod method, ConditionEvents events) {
// 메서드에 붙은 어노테이션 가져오기
Transactional transactionalAnnotation = method.reflect()
.getAnnotation(Transactional.class);

// 어노테이션이 존재하는지
if (transactionalAnnotation != null) {
String transactionManager = Optional.of(
transactionalAnnotation.transactionManager())
.filter(tm -> !tm.isBlank())
.orElse(transactionalAnnotation.value());
if (!transactionManager.equals(LOG_WRITER_TRANSACTION_MANAGER)) {
throw new AssertionError(String.format(
"%s - %s의 transactionManager가 '%s'임",
method.getOwner().getName(),
method.getName(),
transactionManager
));
}
}
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#TODO: 지금은 api 모듈들이 이 모듈을 공용으로 사용하지만 추후에 모듈마다 로깅 설정을 할 수 있도록 할 것

spring:
config:
import:
# @PropertySource는 스프링 컨텍스트가 초기화된 이후 처리되기 때문에
# 여기서 env를 미리 로드하여 logback-spring.xml에서 springProperty를 사용할 수 있도록 합니다.
- "classpath:env-logging.properties"
logging:
discord:
webhook-url: ${DISCORD_WEBHOOK_URL}
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,6 @@
</encoder>
</appender>

<!-- AsyncAppender가 Appender를 감싸서 디스코드 로깅을 비동기로 처리할 수 있도록 함. -->
<appender name="ASYNC_DISCORD_ERROR" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="DISCORD_ERROR"/>
</appender>
<!-- Web hook url은 외부에 공개하면 안되므로 스프링 설정에서 읽어옴 -->
<springProperty name="DISCORD_WEBHOOK_URL" source="logging.discord.webhook-url"/>
<!-- 웹훅을 과도하게 사용하면 디스코드에서 제한을 거니까 ERROR 수준만 로깅 -->
Expand All @@ -65,5 +61,9 @@
<pattern>${NO_COLOR_LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- AsyncAppender가 Appender를 감싸서 디스코드 로깅을 비동기로 처리할 수 있도록 함. -->
<appender name="ASYNC_DISCORD_ERROR" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="DISCORD_ERROR"/>
</appender>

</configuration>
22 changes: 0 additions & 22 deletions modules/infrastructure/spring/build.gradle

This file was deleted.

Loading
Loading