Code Monkey home page Code Monkey logo

ssg_ssag_be_5group's Introduction

SSG.COM 클론코딩

📍 프로젝트 소개

본 프로젝트는 스파로스 아카데미 1기에서 진행한 SSG.COM 신세계몰 클론 코딩 프로젝트입니다.

  • 쓱싹쓱싹(5조)의 백엔드 저장소입니다.
  • Demo

Project Repositories

 

📍 Notion

📍 시스템 아키텍처

시스템 아키텍처

 

📍 개발환경

> OS : Windows 10, Mac OS, Ubuntu 20.04.4 LTS
> Infra : AWS EC2, Nginx
> DB : AWS RDS(MySQL 8.0.28)
> Storage : AWS S3
> Backend : Spring Boot 2.6.10, Gradle(빌드), JPA(DB접근)
> Api : Naver SMS API, Naver Login API, KaKao Login API

설치 및 실행

  1. applicatiom.yml 파일의 datasource, security.oauth2, cloud.aws, sms(네이버 SMS API) 수정 => 사용자 계정, Secret Key 등 입력

  2. SsgBeApplication.java main 함수 실행

 

📍 사용 기술

Frontend

           

Backend

     

Deploy

       

Tools

     

 

📍 디렉터리 구조

└─src
    ├─main
    │  ├─java
    │  │  └─com
    │  │      └─ssg
    │  │          ├─config # config, security, exception, etc.. 관리
    │  │          ├─ssg_be
    │  │          │  ├─cart
    │  │          │  │  ├─application # Service 폴더
    │  │          │  │  ├─domain # 해당 도메인의 entity 폴더
    │  │          │  │  ├─dto # DTO 폴더
    │  │          │  │  ├─infrastructure # Repository 폴더
    │  │          │  │  └─presentation # Controller 폴더
    │  │          │  └─ ... # 나머지 도메인
    │  │          └─utils
    │  │              ├─jwt
    │  │              ├─oauth
    │  │              └─s3
    │  └─resources # application.yml 관리
    └─test

 

📍 개발 산출물

ssg_ssag_be_5group's People

Contributors

ads0070 avatar im-hass avatar k-j-hyeon avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

ahnyongju

ssg_ssag_be_5group's Issues

장바구니 조회 이슈

장바구니 조회 API를 프론트와 연동하는 과정에서 이슈 발생

  1. 반환 DTO가 계층형으로 이루어져 있어서 프론트 단에서 금액을 통계내기가 힘들다.
  2. 장바구니 아이템들이 매장 별로 묶여 있고, 매장 별 중간 통계, 장바구니 전체 통계를 계산 해야 한다.

=> 백에서 장바구니 데이터를 반환할 때, 매장 별로 묶어서 내보내고, DTO에 총 금액, 총 할인 금액, 예상 결제 금액을 포함시켜 반환하도록 변경

[ 변경 전 response 샘플 ]
image

[ 변경 후 response 샘플 ]
image

상품 목록 조회 성능 문제

[이슈]

상품 목록을 조회할 때, 조회하는 데이터의 수가 늘수록 시간이 많이 소요된다.

[테스트 환경]

  • 사용한 DB : AWS RDS MySQL 8.0.28
  • 총 상품 개수 : 12559개
  • 총 리뷰 개수 : 20076개 (상품에 랜덤으로 더미 데이터 리뷰 삽입)
  • 측정 시간 : 총 10번의 API 테스트 평균 시간 측정

[원인]

현재 방식 : 상품 정보를 먼저 전부 불러오고 조회된 상품 개수만큼 반복문으로 해당 상품의 reviewTotal, wishId를 조회한다.
=> 반복문 횟수만큼 reviewTotal의 select문과 wishId의 select문이 호출된다.
=> 로컬에서 서버 가동한 경우 : 회원이 100개 조회 시, 약 2.8초 소요, 1000개 조회 시, 약 27.3초 소요
=> EC2에서 서버 가동한 경우 : 회원이 100개 조회 시, 약 0.2초 소요, 1000개 조회 시, 약 1.8초 소요


[시도 방법]

방법 1 : JPQL을 사용하여 Join으로 한 번에 가져온다.

문제 발생 1 : N+1 문제 발생 -> fetch join으로 가져온다.
문제 발생 2 : JPA 서브 쿼리의 한계 -> from 절에서의 서브 쿼리를 지원하지 않는다. => 해결 실패

방법 2 : 네이티브 쿼리를 사용하여 reviewTotal과 wishId를 조인하여 한 번에 가져온다.

로컬에서 서버 가동한 경우 : 회원이 100개 조회 시, 약 0.14초 소요, 1000개 조회 시, 약 0.20초 소요
EC2에서 서버 가동한 경우 : 회원이 100개 조회 시, 약 0.08초 소요, 1000개 조회 시, 약 0.13초 소요
단점 : JPA를 사용하면서 네이티브 쿼리로 해결하면 DB 분리 시,해당 쿼리문을 쓸 수 없다. + JPA의 장점을 잃게 된다.

방법 3 : API를 분리하여 상품 목록을 먼저 프론트로 반환하고, reviewTotal과 wishId는 프론트의 컴포넌트에서 따로 API를 호출하도록 한다.

단점 : API 통신량이 많아지므로 서버의 부담이 증가된다.


[선택 방법]

AWS EC2가 프리티어 버전이라는 점과 남은 개발 시간을 고려하여 2번 방법으로 진행

CORS 처리

<문제 발생>
프론트와 API로 데이터를 넘기는 과정에서 CORS 문제가 발생

<문제 해결>

  1. main 함수에서 WebMvcConfigurer Bean을 등록해 해결해 보려고 했지만 실패
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }

2. Spring Security를 사용하고 있기 때문에, Cors Filter를 생성하여 문제 해결!

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();
        config.setExposedHeaders(Arrays.asList("Authentication"));
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE"));
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
  • configuration.addAllowedOriginPattern("*");
    특정 패턴의 origin으로 부터 오는 것만 허용한다.
  • configuration.addAllowedMethod("*");
    특정 메소드만 허용한다.
  • configuration.addAllowedHeader("*");
    특정 헤더만 허용한다.
  • configuration.addExposedHeader("authorization");
    추가 헤더, 커스텀 헤더를 지정한다. => jwt를 이용해 사용자 인증을 하기 위한 Authorization이라는 커스텀 헤더를 지정
  • source.registerCorsConfiguration("/**", configuration);
    corsConfiguration 등록

개발 편의상 모든 주소로부터 권한을 허용해 두고, 해당 필터를 SecurityConfig에서 기본 필터 앞에 위치하도록 설정하였다.

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable();
        httpSecurity.httpBasic().disable()
                .authorizeRequests()
                .antMatchers("/users/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .addFilterBefore(corsConfig.corsFilter(),
                        SecurityContextPersistenceFilter.class)
                .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider),
                        UsernamePasswordAuthenticationFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

merge issue

8 / 10

feature/wish(KJH) => local main(ADH ) merge

local main(ADH ) => push(remote)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.