GraphQL Java - Instrumentation

Instrumentation拦截器

经过实现Instrumentation接口,能够观察一个query的执行,或修改运行期的行为。java

最多见的用途是进行性能监控,和自定义日志记录,但它也能够用于完成其余任务。app

建立GraphQL对象时,能够绑定相关的Instrumentation实现。ide

GraphQL.newGraphQL(schema)
                .instrumentation(new TracingInstrumentation())
                .build();

自定义Instrumentation拦截器

Instrumentation实现类须要实现"begin"开头的方法。这个方法会在查询执行的过程当中,在每一个步骤开始以前被调用。性能

每一个回调方法都必须返回一个非空的InstrumentationContext对象,这个对象在本执行步骤完成时会被回调,并告知是否调用成功或是出错(能够获取Throwable对象)。fetch

下面的示例中,给出了一个自定义的Instrumentation拦截器。能够用来测量执行过程的总体执行时间,并将结果存入一个有状态的对象当中。ui

class CustomInstrumentationState implements InstrumentationState {
        private Map<String, Object> anyStateYouLike = new HashMap<>();

        void recordTiming(String key, long time) {
            anyStateYouLike.put(key, time);
        }
    }

    class CustomInstrumentation extends SimpleInstrumentation {
        @Override
        public InstrumentationState createState() {
            //
            // instrumentation state is passed during each invocation of an Instrumentation method
            // and allows you to put stateful data away and reference it during the query execution
            //
            return new CustomInstrumentationState();
        }

        @Override
        public InstrumentationContext<ExecutionResult> beginExecution(InstrumentationExecutionParameters parameters) {
            long startNanos = System.nanoTime();
            return new SimpleInstrumentationContext<ExecutionResult>() {
                @Override
                public void onCompleted(ExecutionResult result, Throwable t) {
                    CustomInstrumentationState state = parameters.getInstrumentationState();
                    state.recordTiming(parameters.getQuery(), System.nanoTime() - startNanos);
                }
            };
        }

        @Override
        public DataFetcher<?> instrumentDataFetcher(DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
            //
            // this allows you to intercept the data fetcher used to fetch a field and provide another one, perhaps
            // that enforces certain behaviours or has certain side effects on the data
            //
            return dataFetcher;
        }

        @Override
        public CompletableFuture<ExecutionResult> instrumentExecutionResult(ExecutionResult executionResult, InstrumentationExecutionParameters parameters) {
            //
            // this allows you to instrument the execution result some how.  For example the Tracing support uses this to put
            // the `extensions` map of data in place
            //
            return CompletableFuture.completedFuture(executionResult);
        }
    }

链式Instrumentation拦截器

能够使用ChainedInstrumentation类,将多个Instrumentation对象进行聚合。ChainedInstrumentation类接收一个Instrumentation对象列表参数,而后按照它们定义的顺序依次调用。this

List<Instrumentation> chainedList = new ArrayList<>();
        chainedList.add(new FooInstrumentation());
        chainedList.add(new BarInstrumentation());
        ChainedInstrumentation chainedInstrumentation = new ChainedInstrumentation(chainedList);

        GraphQL.newGraphQL(schema)
                .instrumentation(chainedInstrumentation)
                .build();

字段验证Instrumentation

FieldValidationInstrumentation拦截器,能够在执行查询前,校验字段和字段参数。若是校验失败,那么执行过程将终止,error信息添加到查询的result当中。日志

能够自定义FieldValidation的实现,或直接使用SimpleFieldValidation类来为每一个字段增长校验规则。code

ExecutionPath fieldPath = ExecutionPath.parse("/user");
        FieldValidation fieldValidation = new SimpleFieldValidation()
                .addRule(fieldPath, new BiFunction<FieldAndArguments, FieldValidationEnvironment, Optional<GraphQLError>>() {
                    @Override
                    public Optional<GraphQLError> apply(FieldAndArguments fieldAndArguments, FieldValidationEnvironment environment) {
                        String nameArg = fieldAndArguments.getFieldArgument("name");
                        if (nameArg.length() > 255) {
                            return Optional.of(environment.mkError("Invalid user name", fieldAndArguments));
                        }
                        return Optional.empty();
                    }
                });

        FieldValidationInstrumentation instrumentation = new FieldValidationInstrumentation(
                fieldValidation
        );

        GraphQL.newGraphQL(schema)
                .instrumentation(instrumentation)
                .build();
相关文章
相关标签/搜索