-
Notifications
You must be signed in to change notification settings - Fork 1
[#23] 장애여부, 수수료 기준으로 pg 라우팅 #25
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| MYSQL_DATABASE=commerce_dev_db | ||
| MYSQL_ROOT_PASSWORD=je1234 | ||
| MYSQL_PORT=3308 | ||
| MYSQL_PORT=3308 | ||
| REDIS_PORT=6379 | ||
| REDIS_PASSWORD=je1234 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package com.commerce.platform.core.application.out; | ||
|
|
||
| import com.commerce.platform.core.domain.enums.PgProvider; | ||
|
|
||
| public abstract class PgStrategy { | ||
|
|
||
| /** | ||
| * pg사별 요청에 따라 [Card | Easy | Phone]PayService 구현체 실행한다. | ||
| * @param request todo dto | ||
| * @return todo 결재응답dto | ||
| */ | ||
| public abstract String process(String request); | ||
|
|
||
| public abstract PgProvider getPgProvider(); | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,16 +3,58 @@ | |
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import java.util.Set; | ||
|
|
||
| @Getter | ||
| @AllArgsConstructor | ||
| public enum PgProvider { | ||
| // todo 여기서 pg사별 지원하는 결제유형을 관리해야되는지 | ||
| // todo 카드-수기, 인증, sms 위한 값을 만들지 이 부분은 생략할지 CardAuthType | ||
| TOSS("토스"), | ||
| OLIVE_NETWORKS("올리브네트웍스"), | ||
| NHN("NHN"), | ||
| NICE_PAYMENTS("나이스페이먼츠"); | ||
|
|
||
| private final String value; | ||
| TOSS( | ||
| Set.of(PayMethod.CARD, PayMethod.EASY_PAY), | ||
| Set.of(PayProvider.SHIN_HAN, PayProvider.KB, PayProvider.NH, | ||
| PayProvider.HYUNDAI, PayProvider.SAMSUNG, PayProvider.BC) | ||
| ), | ||
| NHN( | ||
| Set.of(PayMethod.CARD, PayMethod.EASY_PAY), | ||
| Set.of(PayProvider.NH, PayProvider.HYUNDAI, | ||
| PayProvider.SAMSUNG, PayProvider.BC) | ||
| ), | ||
| NICE_PAYMENTS( | ||
| Set.of(PayMethod.CARD, PayMethod.EASY_PAY), | ||
| Set.of(PayProvider.HANA, PayProvider.LOTTE, | ||
| PayProvider.SAMSUNG, PayProvider.BC) | ||
| ), | ||
|
|
||
| DANAL( | ||
| Set.of(PayMethod.PHONE), | ||
| Set.of(PayProvider.LG, PayProvider.KT, PayProvider.SKT) | ||
|
|
||
| ), | ||
| PAYLETTER( | ||
| Set.of(PayMethod.PHONE), | ||
| Set.of(PayProvider.LG, PayProvider.KT) | ||
| ) | ||
| ; | ||
|
|
||
| private final Set<PayMethod> payMethods; | ||
| private final Set<PayProvider> payProviders; | ||
|
|
||
| public static List<PgProvider> getByPayMethod(PayMethod payMethod, PayProvider payProvider) { | ||
| List<PgProvider> pgProviders = Arrays.stream(PgProvider.values()) | ||
| .filter(pg -> pg.getPayMethods().contains(payMethod)) | ||
| .filter(pg -> pg.getPayProviders().contains(payProvider)) | ||
| .toList(); | ||
|
|
||
| if(pgProviders.isEmpty()) throw new IllegalArgumentException("지원 PG사 없음"); | ||
| return pgProviders; | ||
| } | ||
|
|
||
| public static PgProvider getByPgName(String pgName) { | ||
| return Arrays.stream(PgProvider.values()) | ||
| .filter(pg -> pg.name().equalsIgnoreCase(pgName)) | ||
| .findFirst() | ||
| .orElseThrow(() -> new IllegalArgumentException("미지원 PG사")); | ||
| } | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @f-lab-lyan 멘토님 결제방식 -> 카드/통신사 기준으로 유효한 pg사 추출하기 위해 |
||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| package com.commerce.platform.core.domain.service; | ||
|
|
||
| import com.commerce.platform.core.application.out.PgStrategy; | ||
| import com.commerce.platform.core.domain.enums.PayMethod; | ||
| import com.commerce.platform.core.domain.enums.PayProvider; | ||
| import com.commerce.platform.core.domain.enums.PgProvider; | ||
| import com.commerce.platform.infrastructure.adaptor.PgCacheService; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| /** | ||
| * PG 라우팅 서비스 | ||
| * 결제방식 + 카드사/통신사 => PG | ||
| * return 서버 정상 + 수수료 가장 저렴한 PG | ||
| */ | ||
| @Slf4j | ||
| @Service | ||
| public class PaymentPgRouter { | ||
|
|
||
| private final Map<PgProvider, PgStrategy> pgStrategies; | ||
| private final PgCacheService pgCacheService; | ||
|
|
||
| public PaymentPgRouter(List<PgStrategy> list, PgCacheService pgCacheService) { | ||
| this.pgStrategies = list.stream() | ||
| .collect(Collectors.toMap(PgStrategy::getPgProvider, pg -> pg)); | ||
| this.pgCacheService = pgCacheService; | ||
| } | ||
|
|
||
| /** | ||
| * 결제유형+카드사에 따라 PG 선택 | ||
| * Redis에서 캐싱 | ||
| */ | ||
| public PgStrategy routePg(PayMethod payMethod, PayProvider payProvider) { | ||
|
|
||
| List<PgProvider> supportedPgs = PgProvider.getByPayMethod(payMethod, payProvider); | ||
|
|
||
| PgProvider selectedPg = pgCacheService.getBestPg(payMethod, payProvider, supportedPgs); | ||
|
|
||
| if (selectedPg == null) { | ||
| throw new IllegalStateException("현재 사용 가능한 PG사가 없습니다"); | ||
| } | ||
|
|
||
| return pgStrategies.get(selectedPg); | ||
| } | ||
|
|
||
| /** | ||
| * PG Provider => Strategy 조회 | ||
| */ | ||
| public PgStrategy getPgStrategyByProvider(PgProvider pgProvider) { | ||
| PgStrategy strategy = pgStrategies.get(pgProvider); | ||
| if (strategy == null) { | ||
| throw new IllegalArgumentException("존재하지 않는 PG: " + pgProvider); | ||
| } | ||
| return strategy; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| package com.commerce.platform.infrastructure.adaptor; | ||
|
|
||
| import com.commerce.platform.core.domain.enums.PayMethod; | ||
| import com.commerce.platform.core.domain.enums.PayProvider; | ||
| import com.commerce.platform.core.domain.enums.PgProvider; | ||
| import com.commerce.platform.infrastructure.persistence.PgFeeInfo; | ||
| import com.commerce.platform.infrastructure.persistence.PgFeeInfoRepository; | ||
| import jakarta.annotation.PostConstruct; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.data.redis.core.StringRedisTemplate; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Set; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| /** | ||
| * PG 라우팅을 위한 Redis 캐시 서비스 | ||
| * 수수료 낮은 순으로 정렬된 PG 목록 관리 | ||
| * 장애 PG는 제외 | ||
| */ | ||
| @Slf4j | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class PgCacheService { | ||
|
|
||
| private final StringRedisTemplate redisTemplate; | ||
| private final PgFeeInfoRepository feeInfoRepository; | ||
|
|
||
| private static final String ROUTE_KEY_PREFIX = "pg:route:"; | ||
| private static final String HEALTH_KEY_PREFIX = "pg:health:"; | ||
|
|
||
| /** | ||
| * ZSet에 캐싱 확인 및 캐싱 | ||
| * key= pg:route:CARD:SHIN_HAN | ||
| * score: 수수료율 | ||
| */ | ||
| @PostConstruct | ||
| public void initPgCache() { | ||
| Set<String> keys = redisTemplate.keys(ROUTE_KEY_PREFIX + "*"); | ||
|
|
||
| if(!keys.isEmpty()) return; | ||
|
|
||
| // 전체 캐싱 | ||
| feeInfoRepository.findAllActiveAndValid() | ||
| .forEach(feeInfo -> { | ||
| String key = buildRouteKey(feeInfo.getPayMethod(), feeInfo.getPayProvider()); | ||
|
|
||
| redisTemplate.opsForZSet().add( | ||
| key, | ||
| feeInfo.getPgProvider().name(), | ||
| feeInfo.getFeeRate().doubleValue()); | ||
| }); | ||
| } | ||
|
|
||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @f-lab-lyan 멘토님
|
||
| public PgProvider getBestPg(PayMethod payMethod, PayProvider payProvider, List<PgProvider> supportedPgs) { | ||
| // redis 조회 | ||
| Set<String> pgProviders = getAvailablePgsFromCache(payMethod, payProvider); | ||
|
|
||
| // miss | ||
| if (pgProviders == null || pgProviders.isEmpty()) { | ||
| pgProviders = refreshCache(payMethod, payProvider); | ||
| } | ||
|
|
||
| // 장애 PG 제외 첫번째 선택 | ||
| PgProvider bestPg = null; | ||
| for (String pgName : pgProviders) { | ||
| bestPg = PgProvider.getByPgName(pgName); | ||
| if (supportedPgs.contains(bestPg) && isHealthy(bestPg)) { | ||
| return bestPg; | ||
| } | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * ZSet 수수료 asc | ||
| */ | ||
| private Set<String> getAvailablePgsFromCache(PayMethod payMethod, PayProvider payProvider) { | ||
| String key = buildRouteKey(payMethod, payProvider); | ||
| return redisTemplate.opsForZSet().range(key, 0, -1); | ||
| } | ||
|
|
||
| /** | ||
| * DB에서 수수료 조회 및 Redis 캐싱 | ||
| * ZSet score: 수수료율 | ||
| */ | ||
| public Set<String> refreshCache(PayMethod payMethod, PayProvider payProvider) { | ||
| String key = buildRouteKey(payMethod, payProvider); | ||
| // DB 조회: 수수료 낮은 순 | ||
| List<PgFeeInfo> configs = feeInfoRepository | ||
| .findByPayMethodAndPayProvider(payMethod, payProvider); | ||
|
|
||
| // todo 별도 스레드로 하는것이 좋을지 | ||
| // 기존 캐시 삭제 | ||
| redisTemplate.delete(key); | ||
|
|
||
| for (PgFeeInfo config : configs) { | ||
| redisTemplate.opsForZSet().add( | ||
| key, | ||
| config.getPgProvider().name(), | ||
| config.getFeeRate().doubleValue() | ||
| ); | ||
| } | ||
|
|
||
| return configs.stream() | ||
| .sorted(Comparator.comparing(PgFeeInfo::getFeeRate)) | ||
| .map(pgFeeInfo -> pgFeeInfo.getPgProvider().name()) | ||
| .collect(Collectors.toSet()); | ||
| } | ||
|
|
||
| /** | ||
| * PG 헬스 체크 | ||
| */ | ||
| public boolean isHealthy(PgProvider pgProvider) { | ||
| String healthKey = HEALTH_KEY_PREFIX + pgProvider.name(); | ||
| return redisTemplate.opsForValue().get(healthKey) == null; | ||
| } | ||
|
|
||
| /** | ||
| * PG 장애 | ||
| * TTL: 30m | ||
| */ | ||
| public void markPgAsUnhealthy(PgProvider pgProvider) { | ||
| String healthKey = HEALTH_KEY_PREFIX + pgProvider.name(); | ||
| redisTemplate.opsForValue().set(healthKey, "ERROR", 30, TimeUnit.MINUTES); | ||
| } | ||
|
|
||
| /** | ||
| * Redis Key 생성: pg:route:CARD:SHIN_HAN | ||
| */ | ||
| private String buildRouteKey(PayMethod payMethod, PayProvider payProvider) { | ||
| return ROUTE_KEY_PREFIX + payMethod.name() + ":" + payProvider.name(); | ||
| } | ||
| } | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @f-lab-lyan 멘토님
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| package com.commerce.platform.infrastructure.persistence; | ||
|
|
||
| import com.commerce.platform.core.domain.enums.PayMethod; | ||
| import com.commerce.platform.core.domain.enums.PayProvider; | ||
| import com.commerce.platform.core.domain.enums.PgProvider; | ||
| import jakarta.persistence.*; | ||
| import lombok.AccessLevel; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| import java.math.BigDecimal; | ||
| import java.time.LocalDate; | ||
| import java.time.LocalDateTime; | ||
|
|
||
| /** | ||
| * PG사별 결제방식 + 카드사/통신사 조합의 수수료율 저장 | ||
| */ | ||
| @Getter | ||
| @NoArgsConstructor(access = AccessLevel.PROTECTED) | ||
| @Entity | ||
| @Table(name = "pg_fee_info") | ||
| public class PgFeeInfo { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; | ||
|
|
||
| @Enumerated(EnumType.STRING) | ||
| @Column(nullable = false) | ||
| private PgProvider pgProvider; | ||
|
|
||
| @Enumerated(EnumType.STRING) | ||
| @Column(nullable = false) | ||
| private PayMethod payMethod; | ||
|
|
||
| @Enumerated(EnumType.STRING) | ||
| @Column(nullable = false) | ||
| private PayProvider payProvider; | ||
|
|
||
| @Column(nullable = false, precision = 4, scale = 2) | ||
| private BigDecimal feeRate; | ||
|
|
||
| @Column(nullable = false) | ||
| private boolean isActive; | ||
|
|
||
| @Column(nullable = false, updatable = false) | ||
| private LocalDate frDt; | ||
|
|
||
| @Column(nullable = false, updatable = false) | ||
| private LocalDate toDt; | ||
|
|
||
| @Column(nullable = false, updatable = false) | ||
| private LocalDateTime createdAt; | ||
|
|
||
| @Column(nullable = false) | ||
| private LocalDateTime updatedAt; | ||
|
|
||
| public PgFeeInfo(PgProvider pgProvider, PayMethod payMethod, | ||
| PayProvider payProvider, BigDecimal feeRate, | ||
| LocalDate frDt, LocalDate toDt) { | ||
| this.pgProvider = pgProvider; | ||
| this.payMethod = payMethod; | ||
| this.payProvider = payProvider; | ||
| this.feeRate = feeRate; | ||
| this.isActive = true; | ||
| this.frDt = frDt; | ||
| this.toDt = toDt; | ||
| this.createdAt = LocalDateTime.now(); | ||
| this.updatedAt = LocalDateTime.now(); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@f-lab-lyan 멘토님
각pg 는 PgStrategy 를 구현하고
요청에 따라 해당pg의 Card | Easy | Phone]PayService 를 실행하도록 구현해보려고 합니다.