계측 인터셉터
계측 인터페이스를 구현하면 쿼리의 실행을 관찰, 또는 런타임의 동작을 수정할 수 있습니다.
가장 일반적인 사용은 성능 모니터링 및 사용자 지정 로깅을위한뿐만 아니라 다른 작업을 할 수 있습니다.
당신이 GraphQL 개체를 만들 때, 당신은 달성 관련 계측을 바인딩 할 수 있습니다.
GraphQL.newGraphQL(schema)
.instrumentation(new TracingInstrumentation())
.build();
사용자 정의 계측 인터셉터
계측 구현 클래스는 "시작"의 시작 부분에 메소드를 구현해야합니다. 쿼리 실행 중에이 방법은, 각 단계의 시작 전에 호출했다.
각 콜백 메소드가 실행이이 단계에서 완료되면 개체를 다시 호출 될 객체 InstrumentationContext null이 아닌를 반환하고 호출이 성공 또는 오류가 (당신의 Throwable 객체를 얻을 수 있습니다) 여부를 알려야합니다.
다음의 예는 계측 사용자 정의 인터셉터를 제공. 실행의 전체 실행 시간을 측정하는 데 사용될 수 있으며, 그 결과는 상태의 객체에 저장된다.
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);
}
}
계측 인터셉터 체인
ChainedInstrumentation 클래스 오브젝트 계측 중합 복수 사용할 수있다. 순서 계측 클래스 객체 파라미터의리스트를 수신 ChainedInstrumentation, 순차는 그들이 호에 정의되어있다.
List<Instrumentation> chainedList = new ArrayList<>();
chainedList.add(new FooInstrumentation());
chainedList.add(new BarInstrumentation());
ChainedInstrumentation chainedInstrumentation = new ChainedInstrumentation(chainedList);
GraphQL.newGraphQL(schema)
.instrumentation(chainedInstrumentation)
.build();
현장 검증 계측
당신은 쿼리를 실행하기 전에 FieldValidationInstrumentation 인터셉터는 필드와 필드 매개 변수를 확인합니다. 검사가, 다음 실행이 종료됩니다 실패 할 경우, 오류 정보는 쿼리 이들의 결과에 추가됩니다.
각 필드에 대한 유효성 검사 규칙을 높이기 위해 사용자 정의 구현 FieldValidation 직접 SimpleFieldValidation 클래스가 될 수 있습니다.
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();