Spring GraphQL 客户端使用指南
概述
Spring GraphQL 项目提供了强大的客户端支持,允许开发者通过多种协议(HTTP、WebSocket 和 RSocket)执行 GraphQL 请求。本文将详细介绍 Spring GraphQL 客户端的使用方法,帮助开发者快速掌握这一工具。
核心接口:GraphQlClient
GraphQlClient 是 Spring GraphQL 客户端的核心接口,它定义了一套与底层传输协议无关的统一工作流。这意味着无论使用哪种传输协议,执行请求的方式都是相同的。
Spring GraphQL 提供了以下几种特定协议的客户端实现:
- HttpSyncGraphQlClient - 基于同步 HTTP 协议
- HttpGraphQlClient - 基于异步 HTTP 协议
- WebSocketGraphQlClient - 基于 WebSocket 协议
- RSocketGraphQlClient - 基于 RSocket 协议
每种客户端都有自己的构建器(Builder),用于配置特定于该传输协议的选项。
客户端类型详解
1. HTTP 同步客户端
HttpSyncGraphQlClient 使用 Spring 的 RestClient 通过阻塞式传输契约和拦截器链执行 GraphQL 请求。
// 创建同步客户端
HttpSyncGraphQlClient client = HttpSyncGraphQlClient.builder()
.url("https://example.com/graphql")
.build();
// 修改客户端配置
HttpSyncGraphQlClient newClient = client.mutate()
.header("Authorization", "Bearer token")
.build();
2. HTTP 异步客户端
HttpGraphQlClient 使用 Spring 的 WebClient 通过非阻塞式传输契约和拦截器链执行 GraphQL 请求。
// 创建异步客户端
HttpGraphQlClient client = HttpGraphQlClient.builder()
.url("https://example.com/graphql")
.build();
// 修改客户端配置
HttpGraphQlClient newClient = client.mutate()
.header("Authorization", "Bearer token")
.build();
3. WebSocket 客户端
WebSocketGraphQlClient 通过共享的 WebSocket 连接执行 GraphQL 请求,适合需要长连接的场景。
// 创建 WebSocket 客户端
WebSocketGraphQlClient client = WebSocketGraphQlClient.builder()
.url("wss://example.com/graphql")
.build();
// 启用心跳保持连接
client.start().block();
client.mutate().keepAlive(Duration.ofMinutes(1)).build();
WebSocket 客户端是面向连接的,需要先建立连接才能发送请求。它支持多路复用,所有请求共享同一个连接。
4. RSocket 客户端
RSocketGraphQlClient 使用 RSocket 协议执行 GraphQL 请求,同样需要先建立会话。
// 创建 RSocket 客户端
RSocketGraphQlClient client = RSocketGraphQlClient.builder()
.tcp("example.com", 6565)
.build();
// 显式建立会话
client.start().block();
执行请求
Spring GraphQL 客户端提供了两种主要的请求执行方式:
1. 检索模式 (Retrieve)
// 同步方式
String name = client.document("{ project(slug:\"spring-framework\") { name } }")
.retrieve("project.name")
.toEntity(String.class);
// 异步方式
Mono<String> nameMono = client.document("{ project(slug:\"spring-framework\") { name } }")
.retrieve("project.name")
.toEntity(String.class);
2. 执行模式 (Execute)
// 同步方式
GraphQlResponse response = client.document("{ project(slug:\"spring-framework\") { name } }")
.execute();
// 异步方式
Mono<GraphQlResponse> responseMono = client.document("{ project(slug:\"spring-framework\") { name } }")
.execute();
文档来源
Spring GraphQL 支持从类路径下的 .graphql 或 .gql 文件中加载 GraphQL 查询:
# src/main/resources/graphql-documents/projectReleases.graphql
query projectReleases($slug: ID!) {
project(slug: $slug) {
name
releases {
version
}
}
}
List<String> versions = client.documentName("projectReleases")
.variable("slug", "spring-framework")
.retrieve("project.releases[*].version")
.toEntityList(String.class);
订阅请求
对于需要流式数据的订阅请求,可以使用支持流式传输的客户端:
// 使用 WebSocket 客户端订阅
Flux<String> comments = client.document("subscription { commentAdded(postId:123) { content } }")
.retrieveSubscription("commentAdded.content")
.toEntity(String.class);
comments.subscribe(content -> System.out.println("New comment: " + content));
拦截器
Spring GraphQL 客户端支持拦截器机制,可以在请求处理前后插入自定义逻辑:
// 同步拦截器
class MySyncInterceptor implements SyncGraphQlClientInterceptor {
@Override
public GraphQlResponse intercept(Request request, Chain chain) {
System.out.println("Before request: " + request.getDocument());
GraphQlResponse response = chain.next(request);
System.out.println("After response");
return response;
}
}
// 异步拦截器
class MyInterceptor implements GraphQlClientInterceptor {
@Override
public Mono<GraphQlResponse> intercept(Request request, Chain chain) {
System.out.println("Before request: " + request.getDocument());
return chain.next(request)
.doOnNext(response -> System.out.println("After response"));
}
}
DGS Codegen 集成
Spring GraphQL 支持与 Netflix 的 DGS Codegen 集成,可以通过生成的客户端 API 类来构建请求:
DgsGraphQlClient dgsClient = DgsGraphQlClient.create(client);
List<Book> books = dgsClient.request(new BooksGraphQLQuery())
.projection(new BooksProjectionRoot<>().id().name())
.retrieveSync("books")
.toEntityList(Book.class);
总结
Spring GraphQL 客户端提供了强大而灵活的功能,支持多种传输协议和多种请求方式。无论是简单的查询还是复杂的订阅场景,都能找到合适的解决方案。通过本文的介绍,开发者应该能够快速上手并充分利用 Spring GraphQL 客户端的功能。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



