PHpullh
학습 라이브러리/Java/API 게이트웨이 패턴

JAVA · 디자인패턴

API 게이트웨이 패턴

마이크로서비스 앞단의 API 게이트웨이 역할과 구현 개념입니다.

디자인패턴고급APIGateway게이트웨이마이크로서비스라우팅

핵심 설명

마이크로서비스 앞단의 API 게이트웨이 역할과 구현 개념입니다.

Java code

import java.util.*;
import java.util.concurrent.*;

public class APIGateway {
    // 서비스 라우팅
    record Route(String path, String serviceUrl) {}

    static class Gateway {
        private final Map<String, Route> routes = new HashMap<>();
        private final Map<String, String> rateLimits = new HashMap<>();

        void addRoute(String path, String serviceUrl) {
            routes.put(path, new Route(path, serviceUrl));
        }

        String handle(String path, String apiKey) {
            // 1. 인증
            if (apiKey == null || apiKey.isEmpty()) {
                return "{error: 401, message: '인증 필요'}";
            }

            // 2. 속도 제한
            String limitKey = apiKey + ":" + path;
            rateLimits.merge(limitKey, "1", (old, v) -> {
                int count = Integer.parseInt(old) + 1;
                return String.valueOf(count);
            });
            if (Integer.parseInt(rateLimits.get(limitKey)) > 100) {
                return "{error: 429, message: '요청 한도 초과'}";
            }

            // 3. 라우팅
            Route route = routes.get(path);
            if (route == null) {
                return "{error: 404, message: '경로 없음'}";
            }

            // 4. 서비스 호출 (실제로는 HTTP 클라이언트 사용)
            return "{data: '" + route.serviceUrl() + " 응답'}";
        }
    }

    public static void main(String[] args) {
        Gateway gw = new Gateway();
        gw.addRoute("/users", "http://user-service:8080");
        gw.addRoute("/orders", "http://order-service:8081");

        System.out.println(gw.handle("/users", "key-123"));
        System.out.println(gw.handle("/orders", ""));
        System.out.println(gw.handle("/unknown", "key-123"));
    }
}

학습 팁

API 게이트웨이는 인증, 속도 제한, 로깅, 캐싱, 로드 밸런싱 등의 횡단 관심사를 중앙화합니다. Spring Cloud Gateway가 대표적입니다.

주의할 점

게이트웨이가 단일 장애점(SPOF)이 될 수 있습니다. 반드시 이중화(HA)하고 헬스체크를 구성하세요.

자주 묻는 질문

API 게이트웨이 패턴란 무엇인가요?

마이크로서비스 앞단의 API 게이트웨이 역할과 구현 개념입니다.

API 게이트웨이 패턴 학습 시 주의할 점은 무엇인가요?

게이트웨이가 단일 장애점(SPOF)이 될 수 있습니다. 반드시 이중화(HA)하고 헬스체크를 구성하세요.