티스토리 뷰

카테고리 없음

GraphQlClient 소개

행복[HappY] 2025. 3. 14. 00:00

GraphQlClient에 대한 설명

GraphQlClient는 Spring for GraphQL에서 제공하는 GraphQL API를 호출하는 클라이언트입니다.
Spring 애플리케이션에서 GraphQL 서버와 상호작용할 수 있도록 설계된 비동기(reactive) 또는 동기 방식의 HTTP 클라이언트이며, GraphQL 쿼리를 실행하고 응답을 가져오는 역할을 합니다.

 

 

 

1. GraphQlClient의 역할

GraphQL은 REST API와 달리 하나의 엔드포인트에서 원하는 데이터만 요청할 수 있는 강력한 쿼리 언어입니다.
Spring 애플리케이션에서 GraphQL API를 호출하려면 GraphQlClient를 활용할 수 있습니다.

 

주요 기능

  1. GraphQL 서버에 쿼리(Query) 및 변형(Mutation) 요청
    • GraphQlClient를 사용하면 GraphQL 서버에 요청을 보낼 수 있습니다.
  2. 비동기 및 동기 방식 요청 지원
    • Mono<T> 및 Flux<T>를 활용한 비동기 요청을 지원합니다.
    • executeSync()를 사용한 동기 요청도 가능합니다.
  3. 변수(Variables) 지원
    • GraphQL 쿼리에서 변수를 전달하여 요청을 동적으로 구성할 수 있습니다.
  4. 응답(Response) 매핑
    • GraphQL 응답을 Java 객체로 매핑하여 사용할 수 있습니다.
  5. HTTP 및 WebSocket 기반 GraphQL 요청 지원
    • HTTP 요청뿐만 아니라 WebSocket을 통한 구독(Subscription)도 가능하도록 지원합니다.

 

 

 

2. GraphQlClient 사용 방법

예제 1: 기본적인 GraphQlClient 사용

아래 예제에서는 GraphQlClient를 사용하여 GraphQL API에 요청을 보냅니다.

 

1. GraphQlClient 빈 등록

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.client.HttpGraphQlClient;

@Configuration
public class GraphQlClientConfig {

    @Bean
    public GraphQlClient graphQlClient() {
        return HttpGraphQlClient.builder()
                .url("http://localhost:8080/graphql")
                .build();
    }
}

설명

  • HttpGraphQlClient.builder()를 사용하여 HTTP 기반의 GraphQL 클라이언트를 생성합니다.
  • url("http://localhost:8080/graphql")를 통해 GraphQL 서버의 엔드포인트를 지정합니다.

 

2. GraphQL 쿼리 요청

GraphQL을 호출하여 특정 사용자의 정보를 가져오는 예제입니다.

import org.springframework.graphql.client.GraphQlClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class UserService {

    private final GraphQlClient graphQlClient;

    public UserService(GraphQlClient graphQlClient) {
        this.graphQlClient = graphQlClient;
    }

    public Mono<User> getUserById(String userId) {
        String query = """
            query($id: String!) {
                user(id: $id) {
                    id
                    name
                    email
                }
            }
        """;

        return graphQlClient.document(query)
                .variable("id", userId)
                .retrieve("user")
                .toEntity(User.class);
    }
}

설명

  • GraphQL 쿼리를 정의하여 사용자 정보를 요청합니다.
  • variable("id", userId)를 통해 GraphQL 변수($id)를 전달할 수 있습니다.
  • retrieve("user")를 사용하여 GraphQL 응답에서 "user" 필드를 추출합니다.
  • .toEntity(User.class)를 통해 응답을 User 객체로 변환합니다.

 

예제 2: GraphQL Mutation 요청

데이터를 변경하는 GraphQL Mutation 요청을 수행하는 예제입니다.

import org.springframework.graphql.client.GraphQlClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class UserService {

    private final GraphQlClient graphQlClient;

    public UserService(GraphQlClient graphQlClient) {
        this.graphQlClient = graphQlClient;
    }

    public Mono<User> createUser(String name, String email) {
        String mutation = """
            mutation($name: String!, $email: String!) {
                createUser(name: $name, email: $email) {
                    id
                    name
                    email
                }
            }
        """;

        return graphQlClient.document(mutation)
                .variable("name", name)
                .variable("email", email)
                .retrieve("createUser")
                .toEntity(User.class);
    }
}

설명

  • GraphQL mutation을 정의하여 새로운 사용자를 생성합니다.
  • .variable("name", name).variable("email", email)을 통해 동적으로 값을 전달할 수 있습니다.

 

예제 3: GraphQL Subscription (WebSocket)

GraphQL subscription을 사용하면 실시간 데이터 업데이트를 받을 수 있습니다.

import org.springframework.graphql.client.WebSocketGraphQlClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

@Service
public class NotificationService {

    private final WebSocketGraphQlClient graphQlClient;

    public NotificationService(WebSocketGraphQlClient graphQlClient) {
        this.graphQlClient = graphQlClient;
    }

    public Flux<Notification> subscribeToNotifications() {
        String subscription = """
            subscription {
                notificationReceived {
                    id
                    message
                }
            }
        """;

        return graphQlClient.document(subscription)
                .retrieve("notificationReceived")
                .toEntity(Notification.class);
    }
}

설명

  • WebSocketGraphQlClient를 사용하여 GraphQL Subscription을 활성화합니다.
  • Flux<Notification>을 반환하여 비동기적으로 데이터 업데이트를 받을 수 있도록 설정합니다.

 

 

 

3. GraphQlClient의 주요 메서드

메서드 설명

document(String queryOrMutation) 실행할 GraphQL 쿼리 또는 뮤테이션을 지정
variable(String name, Object value) GraphQL 변수 값을 설정
retrieve(String fieldName) 응답에서 특정 필드 값을 추출
toEntity(Class<T> type) 응답을 Java 객체로 변환
execute() GraphQL 요청을 실행하고 GraphQlResponse 객체를 반환
executeSync() 동기적으로 GraphQL 요청을 실행

 

 

 

4. GraphQlClient 사용 시 주의할 점

  1. GraphQL 스키마를 미리 확인해야 합니다.
    • 요청을 보내기 전에 GraphQL 서버의 스키마(schema.graphqls)를 확인해야 합니다.
  2. HTTP vs WebSocket 선택
    • HttpGraphQlClient: 일반적인 쿼리(Query) 및 변형(Mutation) 요청에 사용
    • WebSocketGraphQlClient: 실시간 데이터(Subscription) 처리에 사용
  3. 비동기 방식 사용 시 Mono와 Flux의 차이를 이해해야 합니다.
    • Mono<T> → 하나의 응답 값만 반환
    • Flux<T> → 스트리밍 데이터를 반환
  4. GraphQL 서버의 CORS 정책을 고려해야 합니다.
    • 클라이언트가 다른 도메인에서 실행될 경우, GraphQL 서버의 CORS 설정을 조정해야 합니다.

 

 

 

5. 요약

  • GraphQlClient는 Spring WebFlux 기반 GraphQL API 클라이언트입니다.
  • 쿼리(Query), 변형(Mutation), 구독(Subscription)을 수행할 수 있습니다.
  • HTTP 및 WebSocket 방식 모두 지원하며, Mono<T>와 Flux<T>를 사용한 비동기 요청이 가능합니다.
  • GraphQL 변수 지원 및 응답 매핑을 제공하여 더욱 유연한 API 호출이 가능합니다.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함