Java源码示例:graphql.execution.instrumentation.Instrumentation
示例1
@PostConstruct
public void init() throws IOException {
URL url = Resources.getResource("starWarsSchemaAnnotated.graphqls");
String sdl = Resources.toString(url, Charsets.UTF_8);
GraphQLSchema graphQLSchema = buildSchema(sdl);
//
// This example uses the DataLoader technique to ensure that the most efficient
// loading of data (in this case StarWars characters) happens. We pass that to data
// fetchers via the graphql context object.
//
DataLoaderDispatcherInstrumentation dlInstrumentation =
new DataLoaderDispatcherInstrumentation(dataLoaderRegistry, newOptions().includeStatistics(true));
Instrumentation instrumentation = new ChainedInstrumentation(
asList(new TracingInstrumentation(), dlInstrumentation)
);
this.graphQL = GraphQL.newGraphQL(graphQLSchema).instrumentation(instrumentation).build();
}
示例2
static CompletableFuture<ExecutionResult> executeGraphQLRequest(
GraphQLRequest request,
ByteBuf byteBuf,
DataLoaderRegistry registry,
GraphQLSchema graphQLSchema,
Instrumentation instrumentation) {
ExecutionInput.Builder builder =
ExecutionInput.newExecutionInput()
.query(request.getQuery())
.operationName(request.getOperationName())
.variables(request.getVariables())
.context(byteBuf)
.executionId(ExecutionId.generate());
if (registry != null) {
builder.dataLoaderRegistry(registry);
}
ExecutionInput executionInput = builder.build();
return GraphQL.newGraphQL(graphQLSchema)
.instrumentation(instrumentation)
.build()
.executeAsync(executionInput);
}
示例3
public static Instrumentation apiFutureInstrumentation() {
return new SimpleInstrumentation() {
@Override
public DataFetcher<?> instrumentDataFetcher(
DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
return (DataFetcher<Object>)
dataFetchingEnvironment -> {
Object data = dataFetcher.get(dataFetchingEnvironment);
if (data instanceof ApiFuture) {
return FutureConverter.toCompletableFuture(
apiFutureToListenableFuture((ApiFuture<?>) data));
}
return data;
};
}
};
}
示例4
@PostConstruct
public void init() throws IOException {
URL url = Resources.getResource("starWarsSchemaAnnotated.graphqls");
String sdl = Resources.toString(url, Charsets.UTF_8);
GraphQLSchema graphQLSchema = buildSchema(sdl);
Instrumentation instrumentation = new TracingInstrumentation();
this.graphQL = GraphQL.newGraphQL(graphQLSchema).instrumentation(instrumentation).build();
}
示例5
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
DataLoaderRegistry dataLoaderRegistry = registryProvider.get();
Instrumentation instrumentation =
new ChainedInstrumentation(
Arrays.asList(
GuavaListenableFutureSupport.listenableFutureInstrumentation(),
new TracingInstrumentation()));
GraphQL graphql = GraphQL.newGraphQL(schema).instrumentation(instrumentation).build();
Map<String, Object> json = readJson(req);
String query = (String) json.get("query");
if (query == null) {
resp.setStatus(400);
return;
}
String operationName = (String) json.get("operationName");
Map<String, Object> variables = getVariables(json.get("variables"));
ExecutionInput executionInput =
ExecutionInput.newExecutionInput()
.query(query)
.operationName(operationName)
.variables(variables)
.dataLoaderRegistry(dataLoaderRegistry)
.context(dataLoaderRegistry)
.build();
ExecutionResult executionResult = graphql.execute(executionInput);
resp.setContentType("application/json");
resp.setStatus(HttpServletResponse.SC_OK);
GSON.toJson(executionResult.toSpecification(), resp.getWriter());
logger.info("stats: " + dataLoaderRegistry.getStatistics());
}
示例6
/**
* Converts a {@link ListenableFuture} to a Java8 {@link java.util.concurrent.CompletableFuture}.
*
* <p>{@see CompletableFuture} is supported by the provided {@link
* graphql.execution.AsyncExecutionStrategy}.
*
* <p>Note: This should be installed before any other instrumentation.
*/
public static Instrumentation listenableFutureInstrumentation(Executor executor) {
return new SimpleInstrumentation() {
@Override
public DataFetcher<?> instrumentDataFetcher(
DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
return (DataFetcher<Object>)
dataFetchingEnvironment -> {
Object data = dataFetcher.get(dataFetchingEnvironment);
if (data instanceof ListenableFuture) {
ListenableFuture<Object> listenableFuture = (ListenableFuture<Object>) data;
CompletableFuture<Object> completableFuture = new CompletableFuture<>();
Futures.addCallback(
listenableFuture,
new FutureCallback<Object>() {
@Override
public void onSuccess(Object result) {
completableFuture.complete(result);
}
@Override
public void onFailure(Throwable t) {
completableFuture.completeExceptionally(t);
}
},
executor);
return completableFuture;
}
return data;
};
}
};
}
示例7
@Bean
public Instrumentation addFederatedTracing() {
return new FederatedTracingInstrumentation(new FederatedTracingInstrumentation.Options(true));
}
示例8
GraphQLServerRequestStream(
DataLoaderRegistry registry, Instrumentation instrumentation, GraphQLSchema graphQLSchema) {
this.registry = registry;
this.instrumentation = instrumentation;
this.graphQLSchema = graphQLSchema;
}
示例9
GraphQLServerRequestResponse(
DataLoaderRegistry registry, Instrumentation instrumentation, GraphQLSchema graphQLSchema) {
this.registry = registry;
this.instrumentation = instrumentation;
this.graphQLSchema = graphQLSchema;
}
示例10
@Override
public void onWebSocketText(String graphqlQuery) {
log.info("Websocket said {}", graphqlQuery);
QueryParameters parameters = QueryParameters.from(graphqlQuery);
ExecutionInput executionInput = ExecutionInput.newExecutionInput()
.query(parameters.getQuery())
.variables(parameters.getVariables())
.operationName(parameters.getOperationName())
.build();
Instrumentation instrumentation = new ChainedInstrumentation(
singletonList(new TracingInstrumentation())
);
//
// In order to have subscriptions in graphql-java you MUST use the
// SubscriptionExecutionStrategy strategy.
//
GraphQL graphQL = GraphQL
.newGraphQL(graphqlPublisher.getGraphQLSchema())
.instrumentation(instrumentation)
.build();
ExecutionResult executionResult = graphQL.execute(executionInput);
Publisher<ExecutionResult> stockPriceStream = executionResult.getData();
stockPriceStream.subscribe(new Subscriber<ExecutionResult>() {
@Override
public void onSubscribe(Subscription s) {
subscriptionRef.set(s);
request(1);
}
@Override
public void onNext(ExecutionResult er) {
log.debug("Sending stick price update");
try {
Object stockPriceUpdate = er.getData();
getRemote().sendString(JsonKit.toJsonString(stockPriceUpdate));
} catch (IOException e) {
e.printStackTrace();
}
request(1);
}
@Override
public void onError(Throwable t) {
log.error("Subscription threw an exception", t);
getSession().close();
}
@Override
public void onComplete() {
log.info("Subscription complete");
getSession().close();
}
});
}
示例11
private void handleStarWars(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
//
// this builds out the parameters we need like the graphql query from the http request
QueryParameters parameters = QueryParameters.from(httpRequest);
if (parameters.getQuery() == null) {
//
// how to handle nonsensical requests is up to your application
httpResponse.setStatus(400);
return;
}
ExecutionInput.Builder executionInput = newExecutionInput()
.query(parameters.getQuery())
.operationName(parameters.getOperationName())
.variables(parameters.getVariables());
//
// the context object is something that means something to down stream code. It is instructions
// from yourself to your other code such as DataFetchers. The engine passes this on unchanged and
// makes it available to inner code
//
// the graphql guidance says :
//
// - GraphQL should be placed after all authentication middleware, so that you
// - have access to the same session and user information you would in your
// - HTTP endpoint handlers.
//
StarWarsWiring.Context context = new StarWarsWiring.Context();
executionInput.context(context);
//
// you need a schema in order to execute queries
GraphQLSchema schema = buildStarWarsSchema();
//
// This example uses the DataLoader technique to ensure that the most efficient
// loading of data (in this case StarWars characters) happens. We pass that to data
// fetchers via the graphql context object.
//
DataLoaderRegistry dataLoaderRegistry = context.getDataLoaderRegistry();
DataLoaderDispatcherInstrumentation dlInstrumentation =
new DataLoaderDispatcherInstrumentation(dataLoaderRegistry, newOptions().includeStatistics(true));
Instrumentation instrumentation = new ChainedInstrumentation(
asList(new TracingInstrumentation(), dlInstrumentation)
);
// finally you build a runtime graphql object and execute the query
GraphQL graphQL = GraphQL
.newGraphQL(schema)
// instrumentation is pluggable
.instrumentation(instrumentation)
.build();
ExecutionResult executionResult = graphQL.execute(executionInput.build());
returnAsJson(httpResponse, executionResult);
}
示例12
@JsonIgnore
public void setInstrumentations(@Nullable List<Instrumentation> instrumentations) {
this.instrumentations = Optional.ofNullable(instrumentations).orElseGet(ArrayList::new);
}
示例13
/**
* Converts a {@link ListenableFuture} to a Java8 {@link java.util.concurrent.CompletableFuture}.
*
* <p>{@see CompletableFuture} is supported by the provided {@link
* graphql.execution.AsyncExecutionStrategy}.
*
* <p>Note: This should be installed before any other instrumentation.
*/
public static Instrumentation listenableFutureInstrumentation() {
return listenableFutureInstrumentation(MoreExecutors.directExecutor());
}