SpringBoot

SpringBoot - 백엔드 개발할 때 알아두면 좋은 기술 스택

hminor 2024. 11. 16. 23:17
반응형

1. 프로젝트 관리: Maven 또는 Gradle

Spring Boot 프로젝트는 MavenGradle 중 하나를 빌드 도구로 선택합니다.

  • Maven: 직관적인 XML 구조와 방대한 커뮤니티 지원으로 안정적인 환경 제공.
  • Gradle: 빌드 속도가 빠르고, 직관적인 DSL을 통해 설정 간소화 가능.

선택 팁: 프로젝트 규모팀의 경험에 따라 도구를 결정하세요. Maven이 익숙한 팀이라면 Maven을, 최신 트렌드와 속도를 중요시한다면 Gradle을 추천합니다.

 

2. 데이터베이스: JPA/Hibernate + QueryDSL

  • JPA/Hibernate: 데이터베이스 ORM(Object-Relational Mapping) 도구로, 데이터베이스 작업을 자바 객체와 매핑하여 생산성을 향상시킵니다.
  • QueryDSL: 복잡한 쿼리 작성을 더욱 간편하게 만들어줍니다.
@Repository
@RequiredArgsConstructor
public class UserRepositoryImpl implements UserRepositoryCustom {
    private final JPAQueryFactory queryFactory;

    public List<User> findUsersByName(String name) {
        return queryFactory.selectFrom(user)
                           .where(user.name.eq(name))
                           .fetch();
    }
}

활용 팁: 기본 CRUD는 JPA를, 복잡한 조회 쿼리는 QueryDSL을 사용하는 방식으로 조합하면 효율적입니다.

 

3. API 통신: RestTemplate vs WebClient

  • RestTemplate: Spring 5 이전 버전에서 주로 사용되던 HTTP 클라이언트. 간단한 요청에는 여전히 유효합니다.
  • WebClient: 비동기 요청을 지원하며, 성능이 중요한 프로젝트에 적합합니다.
WebClient webClient = WebClient.create("https://api.example.com");
String response = webClient.get()
                           .uri("/data")
                           .retrieve()
                           .bodyToMono(String.class)
                           .block();

선택 팁: 새로운 프로젝트라면 WebClient를, 기존 프로젝트와의 호환성이 필요하다면 RestTemplate을 활용하세요.

 

4. 인증 및 보안: Spring Security + JWT

  • Spring Security: 강력한 인증 및 권한 부여 기능을 제공하며, OAuth2 및 JWT와 손쉽게 통합할 수 있습니다.
  • JWT: JSON Web Token은 API 호출마다 인증 정보를 전달할 때 사용됩니다.
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/api/public/**").permitAll()
        .antMatchers("/api/private/**").authenticated()
        .and()
        .addFilter(new JwtAuthenticationFilter(authenticationManager()));
}

활용 팁: 인증이 필요한 API와 공개 API를 명확히 분리하고 Spring Security의 필터 체인을 활용해 보안을 강화하세요.

 

5. 로그 관리: Logback + ELK Stack

  • Logback: Spring Boot의 기본 로깅 프레임워크로, 다양한 설정을 통해 로그를 효율적으로 관리할 수 있습니다.
  • ELK Stack: ElasticSearch, Logstash, Kibana의 조합으로 로그 데이터를 시각화하고 분석하는 데 유용합니다.
logging:
  level:
    root: INFO
  file:
    name: app.log

활용 팁: Logback을 기본 설정으로 활용하되, 대규모 프로젝트에서는 ELK로 전환해 로그를 효율적으로 관리하세요.

 

6. 비동기 처리: Spring Batch + @Async

  • Spring Batch: 대량의 데이터 처리와 예약 작업에 유용한 배치 프레임워크.
  • @Async: 간단한 비동기 작업 처리에 적합합니다.
@Async
public CompletableFuture<String> asyncProcess() {
    return CompletableFuture.completedFuture("작업 완료");
}

활용 팁: 데이터 마이그레이션이나 정기 작업에는 Batch를, 간단한 비동기 처리에는 @Async를 사용하세요.

 

7. 테스트: JUnit5 + MockMVC

  • JUnit5: 유닛 테스트의 기본 도구로, 다양한 확장 기능 제공.
  • MockMVC: 컨트롤러 테스트에 적합한 도구로, HTTP 요청과 응답을 시뮬레이션합니다.
@Test
void shouldReturnDefaultMessage() throws Exception {
    mockMvc.perform(get("/api/hello"))
           .andExpect(status().isOk())
           .andExpect(content().string("Hello World"));
}

활용 팁: MockMVC로 컨트롤러를 테스트하고, 서비스와 레포지토리는 Mockito로 Mocking하여 테스트를 분리하세요.


8. 배포: Docker + Kubernetes

  • Docker: 컨테이너 환경에서 Spring Boot 애플리케이션을 손쉽게 배포 가능.
  • Kubernetes: 대규모 애플리케이션의 확장성과 관리에 유리한 오케스트레이션 도구.
FROM openjdk:17
COPY target/myapp.jar myapp.jar
ENTRYPOINT ["java", "-jar", "myapp.jar"]

활용 팁: Docker 이미지를 생성한 뒤 Kubernetes를 통해 배포 자동화와 확장성을 확보하세요.