Giter Club home page Giter Club logo

product-order's Introduction

상품 주문

  • 상품 주문 토이프로젝트

프로젝트 시작 방법

docker-compose 로 redis 실행

  • docker 를 실행합니다.
  • docker-compose 폴더에 있는 docker-compose-redis.yml 을 실행시킵니다.
docker-compose -f ./docker-compose-redis.yml up -d

redis 동작 확인

  • redis-cli 로 접속해서 ping 명령어를 날리면 동작 확인이 가능합니다.
docker exec -it redis_main redis-cli


ping 명령어 입력
PONT 답변

CoreApiApplication 실행

  • 실행하면서 schema.sql 실행되면서 product_order, product 테이블이 생성되며, 데이터가 INSERT 됩니다.

상품 주문 API 호출

  • 아래는 userId 1002 에 productId 10002 로 100개를 주문합니다. (이미 데이터가 들어가있습니다.)
curl --location --request POST 'localhost:8080/api/v1/orders' \
--header 'Content-Type: application/json' \
--data-raw '{
    "userId" : "user1002",
    "productId" : "product1002",
    "quantity" : 100

}'

상품 주문 확인 API 호출

  • 아래 API 를 호출하면 내가 주문한 내역을 확인할 수 있습니다.
curl --location --request GET 'localhost:8080/api/v1/orders' \
--header 'Content-Type: application/json' \
--data-raw ''

혹시 product 에 대한 재고를 살펴보고 싶으면 H2 접속해서 select 쿼리 날려보면 됩니다.

product-order's People

Contributors

leechoongyon avatar

Watchers

 avatar

product-order's Issues

개발할 것 정리

Redis

  • Redis 분산락 구현
  • Reds 환경 구성

서비스

  • DB Reactive Spring Data 구현
  • Orders GET, POST METHOD 개발
  • 작성한 코드 분석해서 공부
  • 분산락을 획득 후, DB 에 데이터를 저장한다.
  • 상품 테이블에 재고를 (-) 한다.
  • USER, 상품 ID 를 맵핑하는 History 를 저장한다.
  • DB 작업이 끝나면 분산락 Release
  • 위에 작성한 코드 모두가 비동기인지 체크

DB 데이터 저장 개발

개발

  • Orders GET, POST METHOD 개발
  • 작성한 코드 분석해서 공부
  • 분산락을 획득 후, DB 에 데이터를 저장한다.
  • 상품 테이블에 재고를 (-) 한다.
  • USER, 상품 ID 를 맵핑하는 History 를 저장한다.
  • DB 작업이 끝나면 분산락 Release
  • 위에 작성한 코드 모두가 비동기인지 체크

테스트 (재고 관리)

개요

  • 상품 데이터 미리 만들어놓기
  • 동시성 요청 시, 재고만큼 User, Product Mapping 이 생겼는지 체크

초기 데이터 적재 방법

  • src/main/resources 에 schema.sql 파일과 data.sql 파일을 만든다.

sql source

-- schema.sql
CREATE TABLE product (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    stock INT
);


-- data.sql
INSERT INTO product (id, name, stock) VALUES (1, 'MacBook', 1000);
INSERT INTO product (id, name, stock) VALUES (2, 'IPhone', 2000);

테스트

  • 주문 시, 재고 관리랑 상품주문 테이블에 데이터 적재 여부 확인
  • 주문 시, 재고 보다 구매 수량을 초과해서 주문할 시, 예외 확인
  • 재고 100 , 구매 수량 1000으로 주문 시, product 은 예외가 발생하는데 product_order 는 데이터가 쌓이네?

서비스 리팩토링

  • 서비스 layer return 을 dto 로 변환. Mono, Flux 로 안해도 될거 같음
  • 이렇게 생각했는데 막상 예제 소스를 보니 service layer return 값이 Mono, Flux 네

Redis 분산락 개발

개요

  • SETNX 를 통해 KEY 를 저장한 후, DEL 명령어를 통해 락을 해제한다.
  • 2개의 명령어는 원자성을 보장하는 명령어이다.

할일

  • 패키지 위치를 어떻게 잡아야지?
  • 어느 부분에 annotation 을 걸어야 하나?
  • 테스트는 어떻게 하지?

source

@Component
class DistributedLock(
    private val reactiveRedisTemplate: ReactiveRedisTemplate<String, String>,
    @Value("\${redis.lock.timeout}") private val timeout: Long
) {
    fun acquireLock(key: String): Mono<Boolean> {
        // Redis의 SETNX 명령어를 사용하여 락을 획득합니다. (원자성 보장)
        // key : 저장할 키, "" : 저장 value, timeout : TTL 
        return reactiveRedisTemplate.opsForValue().setIfAbsent(key, "", Duration.ofMillis(timeout))
    }
    fun releaseLock(key: String): Mono<Boolean> {
        // Redis의 DEL 명령어를 사용하여 락을 해제합니다. (원자성 보장)
        return reactiveRedisTemplate.delete(key)
    }
}

분산락 관련 할일

할일

  • 분산락 내가 제대로 개발했는지 검토
  • 분산락 공통 annotation 으로 처리 - aop 이용해서
  • 분산락 잡을 때, key 상수로 처리

동시성 테스트

할일

  • 테스트 시나리오 생각해보기
  • 현재 schema.sql 에 아래와 같이 데이터가 들어있음
  • k6 시나리오 작성할 때, product1001 ~ 1005 까지 10개씩 주문하도록 하기
  • 그런 뒤, order(주문) 테이블에는 150개의 count 가 맞는지 확인
  • product 테이블에는 재고가 0인지 확인
  ('product1001', 'Product A', 100),
  ('product1002', 'Product B', 200),
  ('product1003', 'Product C', 300),
  ('product1004', 'Product D', 400),
  ('product1005', 'Product E', 500);
  • k6 테스트 돌렸을 때, 동시성 문제 안생기는지 체크

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.