org.springframework.web.reactive.function.client.ExchangeFunction Java Examples

The following examples show how to use org.springframework.web.reactive.function.client.ExchangeFunction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InstanceExchangeFilterFunctions.java    From Moss with Apache License 2.0 7 votes vote down vote up
public static ExchangeFilterFunction convertLegacyEndpoint(LegacyEndpointConverter converter) {
    return (ClientRequest request, ExchangeFunction next) -> {
        Mono<ClientResponse> clientResponse = next.exchange(request);
        if (request.attribute(ATTRIBUTE_ENDPOINT).map(converter::canConvert).orElse(false)) {
            return clientResponse.flatMap(response -> {
                if (response.headers()
                            .contentType()
                            .map(t -> ACTUATOR_V1_MEDIATYPE.isCompatibleWith(t) ||
                                      APPLICATION_JSON.isCompatibleWith(t))
                            .orElse(false)) {
                    return convertClientResponse(converter::convert, ACTUATOR_V2_MEDIATYPE).apply(response);
                }
                return Mono.just(response);
            });
        }
        return clientResponse;
    };
}
 
Example #2
Source File: WiretapConnectorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void captureAndClaim() {
	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, "/test");
	ClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
			.header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build();

	WiretapConnector wiretapConnector = new WiretapConnector(connector);
	ExchangeFunction function = ExchangeFunctions.create(wiretapConnector);
	function.exchange(clientRequest).block(ofMillis(0));

	WiretapConnector.Info actual = wiretapConnector.claimRequest("1");
	ExchangeResult result = actual.createExchangeResult(Duration.ZERO, null);
	assertEquals(HttpMethod.GET, result.getMethod());
	assertEquals("/test", result.getUrl().toString());
}
 
Example #3
Source File: InstanceExchangeFilterFunctionsTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_retry_using_default() {
    ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(1, emptyMap());

    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")).build();
    ClientResponse response = mock(ClientResponse.class);

    AtomicLong invocationCount = new AtomicLong(0L);
    ExchangeFunction exchange = r -> Mono.fromSupplier(() -> {
        if (invocationCount.getAndIncrement() == 0) {
            throw new IllegalStateException("Test");
        }
        return response;
    });

    StepVerifier.create(filter.filter(request, exchange)).expectNext(response).verifyComplete();
    assertThat(invocationCount.get()).isEqualTo(2);
}
 
Example #4
Source File: InstanceExchangeFilterFunctionsTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_retry_using_endpoint_value_default() {
    ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(0, singletonMap("test", 1));

    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
                                         .attribute(ATTRIBUTE_ENDPOINT, "test")
                                         .build();
    ClientResponse response = mock(ClientResponse.class);

    AtomicLong invocationCount = new AtomicLong(0L);
    ExchangeFunction exchange = r -> Mono.fromSupplier(() -> {
        if (invocationCount.getAndIncrement() == 0) {
            throw new IllegalStateException("Test");
        }
        return response;
    });

    StepVerifier.create(filter.filter(request, exchange)).expectNext(response).verifyComplete();
    assertThat(invocationCount.get()).isEqualTo(2);
}
 
Example #5
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
void should_retry_using_endpoint_value_default() {
	InstanceExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(0, singletonMap("test", 1));

	ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
			.attribute(ATTRIBUTE_ENDPOINT, "test").build();
	ClientResponse response = ClientResponse.create(HttpStatus.OK).build();

	AtomicLong invocationCount = new AtomicLong(0L);
	ExchangeFunction exchange = (r) -> Mono.fromSupplier(() -> {
		if (invocationCount.getAndIncrement() == 0) {
			throw new IllegalStateException("Test");
		}
		return response;
	});

	StepVerifier.create(filter.filter(INSTANCE, request, exchange)).expectNext(response).verifyComplete();
	assertThat(invocationCount.get()).isEqualTo(2);
}
 
Example #6
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
void should_retry_using_default() {
	InstanceExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(1, emptyMap());

	ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")).build();
	ClientResponse response = ClientResponse.create(HttpStatus.OK).build();

	AtomicLong invocationCount = new AtomicLong(0L);
	ExchangeFunction exchange = (r) -> Mono.fromSupplier(() -> {
		if (invocationCount.getAndIncrement() == 0) {
			throw new IllegalStateException("Test");
		}
		return response;
	});

	StepVerifier.create(filter.filter(INSTANCE, request, exchange)).expectNext(response).verifyComplete();
	assertThat(invocationCount.get()).isEqualTo(2);
}
 
Example #7
Source File: EurekaLoadBalancingExchangeFilterFunction.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private Mono<ClientResponse> doExecute(InstanceInfo instance, ClientRequest request, ExchangeFunction next) {
    URI eurekaUri = request.url();
    URI rewrittenURI = rewrite(eurekaUri, instance);

    ClientRequest newRequest = ClientRequest.create(request.method(), rewrittenURI)
            .headers(headers -> headers.addAll(request.headers()))
            .cookies(cookies -> cookies.addAll(request.cookies()))
            .attributes(attributes -> attributes.putAll(request.attributes()))
            .body(request.body()).build();
    return next.exchange(newRequest)
            .doOnNext(response -> {
                if (response.statusCode().is5xxServerError()) {
                    loadBalancer.recordFailure(eurekaUri, instance);
                } else {
                    loadBalancer.recordSuccess(eurekaUri, instance);
                }
            })
            .doOnError(error -> loadBalancer.recordFailure(eurekaUri, instance));
}
 
Example #8
Source File: EurekaLoadBalancingExchangeFilterFunctionTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private ClientResponse execute(String eurekaUri) {
    EurekaLoadBalancingExchangeFilterFunction filter = new EurekaLoadBalancingExchangeFilterFunction(
            eurekaServer.getEurekaClient(), EurekaUris::getServiceName, titusRuntime
    );

    ClientRequest request = mock(ClientRequest.class);
    when(request.url()).thenReturn(URI.create(eurekaUri));
    when(request.method()).thenReturn(HttpMethod.GET);
    when(request.headers()).thenReturn(HttpHeaders.EMPTY);
    when(request.cookies()).thenReturn(HttpHeaders.EMPTY);

    ExchangeFunction next = mock(ExchangeFunction.class);
    when(next.exchange(any())).thenAnswer(invocation -> {
        ClientRequest rewrittenRequest = invocation.getArgument(0);
        ClientResponse clientResponse = mock(ClientResponse.class);
        if (rewrittenRequest.url().getHost().equals("1.0.0.1")) {
            when(clientResponse.statusCode()).thenReturn(HttpStatus.OK);
        } else {
            when(clientResponse.statusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return Mono.just(clientResponse);
    });

    return filter.filter(request, next).block();
}
 
Example #9
Source File: WingtipsSpringWebfluxExchangeFilterFunction.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@Override
public @NotNull Mono<ClientResponse> filter(
    @NotNull ClientRequest request, @NotNull ExchangeFunction next
) {
    // Try to get the base tracing state from the request attributes first.
    Optional<TracingState> tcFromRequestAttributesOpt = request
        .attribute(TracingState.class.getName())
        .map(o -> (TracingState)o);

    // If the request attributes contains a TracingState, then that's what we should use for the request.
    //      Otherwise, we'll just go with whatever's on the current thread.
    Supplier<Mono<ClientResponse>> resultSupplier = () -> doFilterForCurrentThreadTracingState(request, next);
    return tcFromRequestAttributesOpt.map(
        tcFromRequestAttributes -> supplierWithTracing(
            resultSupplier,
            tcFromRequestAttributes
        ).get()
    ).orElseGet(
        resultSupplier
    );
}
 
Example #10
Source File: WebClientRequestsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    this.exchangeFunction = mock(ExchangeFunction.class);
    ClientResponse mockResponse = mock(ClientResponse.class);
    when(this.exchangeFunction.exchange(this.argumentCaptor.capture())).thenReturn(Mono.just(mockResponse));
    this.webClient = WebClient
            .builder()
            .baseUrl(BASE_URL)
            .exchangeFunction(exchangeFunction)
            .build();
}
 
Example #11
Source File: InstanceExchangeFilterFunctionsTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
void should_not_retry_for_put_post_patch_delete() {
	InstanceExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(1, emptyMap());

	AtomicLong invocationCount = new AtomicLong(0L);
	ExchangeFunction exchange = (r) -> Mono.fromSupplier(() -> {
		invocationCount.incrementAndGet();
		throw new IllegalStateException("Test");
	});

	ClientRequest patchRequest = ClientRequest.create(HttpMethod.PATCH, URI.create("/test")).build();
	StepVerifier.create(filter.filter(INSTANCE, patchRequest, exchange))
			.verifyError(IllegalStateException.class);
	assertThat(invocationCount.get()).isEqualTo(1);

	invocationCount.set(0L);
	ClientRequest putRequest = ClientRequest.create(HttpMethod.PUT, URI.create("/test")).build();
	StepVerifier.create(filter.filter(INSTANCE, putRequest, exchange)).verifyError(IllegalStateException.class);
	assertThat(invocationCount.get()).isEqualTo(1);

	invocationCount.set(0L);
	ClientRequest postRequest = ClientRequest.create(HttpMethod.POST, URI.create("/test")).build();
	StepVerifier.create(filter.filter(INSTANCE, postRequest, exchange))
			.verifyError(IllegalStateException.class);
	assertThat(invocationCount.get()).isEqualTo(1);

	invocationCount.set(0L);
	ClientRequest deleteRequest = ClientRequest.create(HttpMethod.DELETE, URI.create("/test")).build();
	StepVerifier.create(filter.filter(INSTANCE, deleteRequest, exchange))
			.verifyError(IllegalStateException.class);
	assertThat(invocationCount.get()).isEqualTo(1);
}
 
Example #12
Source File: TraceWebClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
MonoWebClientTrace(ExchangeFunction next, ClientRequest request,
		TraceExchangeFilterFunction filterFunction) {
	this.next = next;
	this.request = request;
	this.handler = filterFunction.handler();
	this.currentTraceContext = filterFunction.currentTraceContext();
	this.scopePassingTransformer = filterFunction.scopePassingTransformer;
	this.parent = currentTraceContext.get();
}
 
Example #13
Source File: RetryAttemptsResponseHeaderSetter.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
    // Exceptions thrown before return WILL NOT trigger circuit breaker nor retryer.
    return next.exchange(request)
            .map(response -> from(response)
                    .headers(httpHeaders -> httpHeaders.set("Retry-Attempts", valueOf(attempt.incrementAndGet())))
                    .body(response.body(toDataBuffers())) // Need to consume body, otherwise the request will HANG after ReverseProxyFilter.
                    .build());
}
 
Example #14
Source File: HttpRequestInterceptor.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction exchange) {
    HttpRequest httpRequest = request instanceof HttpRequest
            ? (HttpRequest) request
            : new HttpRequest(request);
    HttpRequestExecution requestExecution = exchange instanceof HttpRequestExecution
            ? (HttpRequestExecution) exchange
            : new HttpRequestExecution(mappingName, exchange);
    return requestForwardingInterceptor.forward(httpRequest, requestExecution).cast(ClientResponse.class);
}
 
Example #15
Source File: WingtipsSpringWebfluxExchangeFilterFunctionTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void beforeMethod() {
    resetTracing();

    spanRecorder = new SpanRecorder();
    Tracer.getInstance().addSpanLifecycleListener(spanRecorder);

    initialSpanNameFromStrategy = new AtomicReference<>("span-name-from-strategy-" + UUID.randomUUID().toString());
    strategyInitialSpanNameMethodCalled = new AtomicBoolean(false);
    strategyRequestTaggingMethodCalled = new AtomicBoolean(false);
    strategyResponseTaggingAndFinalSpanNameMethodCalled = new AtomicBoolean(false);
    strategyInitialSpanNameArgs = new AtomicReference<>(null);
    strategyRequestTaggingArgs = new AtomicReference<>(null);
    strategyResponseTaggingArgs = new AtomicReference<>(null);
    tagAndNamingStrategy = new ArgCapturingHttpTagAndSpanNamingStrategy<>(
        initialSpanNameFromStrategy, strategyInitialSpanNameMethodCalled, strategyRequestTaggingMethodCalled,
        strategyResponseTaggingAndFinalSpanNameMethodCalled, strategyInitialSpanNameArgs,
        strategyRequestTaggingArgs, strategyResponseTaggingArgs
    );
    tagAndNamingAdapterMock = mock(HttpTagAndSpanNamingAdapter.class);

    filterSpy = spy(
        new WingtipsSpringWebfluxExchangeFilterFunction(true, tagAndNamingStrategy, tagAndNamingAdapterMock)
    );

    request = ClientRequest
        .create(HttpMethod.PATCH, URI.create("http://localhost:1234/foo/bar?stuff=things"))
        .header("fooHeader", UUID.randomUUID().toString())
        .build();
    responseMock = mock(ClientResponse.class);
    nextExchangeFunctionMock = mock(ExchangeFunction.class);
    nextExchangeFunctionResult = Mono.just(responseMock);

    doReturn(nextExchangeFunctionResult).when(nextExchangeFunctionMock).exchange(any(ClientRequest.class));
}
 
Example #16
Source File: WingtipsSpringWebfluxExchangeFilterFunction.java    From wingtips with Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link HttpRequestTracingUtils#propagateTracingHeaders(HttpObjectForPropagation, Span)} to propagate the
 * current span's tracing state on a the given request's headers, sets a {@link TracingState} request
 * attribute to match the given argument, then returns {@link ExchangeFunction#exchange(ClientRequest)} to
 * continue the chain. The resulting {@link Mono} will also have it's subscriber {@link Context} adjusted
 * to also include the {@link TracingState} via {@link
 * WingtipsSpringWebfluxUtils#subscriberContextWithTracingInfo(Context, TracingState)}.
 *
 * <p>The given {@link TracingState} argument is strictly for adding to the the request attributes and Mono
 * {@link Context}. The headers that are passed on the outbound call will come from {@link
 * Tracer#getCurrentSpan()}, which means the correct tracing state must also be attached to the current thread.
 *
 * @return The result of calling {@link ExchangeFunction#exchange(ClientRequest)} on the request, adjusted
 * to propagate the tracing state on outbound headers.
 */
protected @NotNull Mono<ClientResponse> propagateTracingHeadersAndExecute(
    @NotNull ClientRequest request,
    @NotNull ExchangeFunction next,
    @Nullable TracingState tracingStateForReqAttrsAndMonoContext
) {
    // Create a mutable builder from the request.
    ClientRequest.Builder requestWithTracingHeadersBuilder = ClientRequest.from(request);

    // Propagate tracing headers
    HttpRequestTracingUtils.propagateTracingHeaders(
        requestWithTracingHeadersBuilder::header,
        Tracer.getInstance().getCurrentSpan()
    );

    // Add the tracing state to the request attributes if the tracing state is non-null.
    if (tracingStateForReqAttrsAndMonoContext != null) {
        requestWithTracingHeadersBuilder.attribute(TracingState.class.getName(),
                                                   tracingStateForReqAttrsAndMonoContext);
    }

    // Execute the request/interceptor chain, using the request with tracing headers.
    return next.exchange(requestWithTracingHeadersBuilder.build())
               .subscriberContext(
                   // Add the tracing state to the Mono Context if it's non-null.
                   c -> (tracingStateForReqAttrsAndMonoContext == null)
                        ? c
                        : subscriberContextWithTracingInfo(c, tracingStateForReqAttrsAndMonoContext)
               );
}
 
Example #17
Source File: EurekaLoadBalancingExchangeFilterFunction.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
    URI eurekaUri;
    try {
        eurekaUri = EurekaUris.failIfEurekaUriInvalid(request.url());
    } catch (IllegalArgumentException e) {
        logger.warn(e.getMessage());
        logger.debug("Stack trace", e);
        return Mono.just(ClientResponse.create(HttpStatus.SERVICE_UNAVAILABLE).body(e.getMessage()).build());
    }

    return loadBalancer.chooseNext(eurekaUri)
            .map(instance -> doExecute(instance, request, next))
            .orElseGet(() -> doFailOnNoInstance(eurekaUri));
}
 
Example #18
Source File: TracingClientResponseMono.java    From java-spring-web with Apache License 2.0 5 votes vote down vote up
TracingClientResponseMono(
        final ClientRequest clientRequest,
        final ExchangeFunction next,
        final Tracer tracer,
        final List<WebClientSpanDecorator> spanDecorators
) {
    this.request = clientRequest;
    this.next = next;
    this.tracer = tracer;
    this.spanDecorators = spanDecorators;
}
 
Example #19
Source File: TracingClientResponseMono.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
TracingClientResponseMono(
    final ClientRequest clientRequest,
    final ExchangeFunction next,
    final Tracer tracer,
    final List<WebClientSpanDecorator> spanDecorators
) {
  this.request = clientRequest;
  this.next = next;
  this.tracer = tracer;
  this.spanDecorators = spanDecorators;
}
 
Example #20
Source File: WiretapConnectorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void captureAndClaim() {
	ClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, "/test");
	ClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	ClientHttpConnector connector = (method, uri, fn) -> fn.apply(request).then(Mono.just(response));

	ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("/test"))
			.header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build();

	WiretapConnector wiretapConnector = new WiretapConnector(connector);
	ExchangeFunction function = ExchangeFunctions.create(wiretapConnector);
	function.exchange(clientRequest).block(ofMillis(0));

	WiretapConnector.Info actual = wiretapConnector.claimRequest("1");
	ExchangeResult result = actual.createExchangeResult(Duration.ZERO, null);
	assertEquals(HttpMethod.GET, result.getMethod());
	assertEquals("/test", result.getUrl().toString());
}
 
Example #21
Source File: InstanceExchangeFilterFunctionsTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_retry_for_put_post_patch_delete() {
    ExchangeFilterFunction filter = InstanceExchangeFilterFunctions.retry(1, emptyMap());

    AtomicLong invocationCount = new AtomicLong(0L);
    ExchangeFunction exchange = r -> Mono.fromSupplier(() -> {
        invocationCount.incrementAndGet();
        throw new IllegalStateException("Test");
    });

    ClientRequest patchRequest = ClientRequest.create(HttpMethod.PATCH, URI.create("/test")).build();
    StepVerifier.create(filter.filter(patchRequest, exchange)).expectError(IllegalStateException.class).verify();
    assertThat(invocationCount.get()).isEqualTo(1);

    invocationCount.set(0L);
    ClientRequest putRequest = ClientRequest.create(HttpMethod.PUT, URI.create("/test")).build();
    StepVerifier.create(filter.filter(putRequest, exchange)).expectError(IllegalStateException.class).verify();
    assertThat(invocationCount.get()).isEqualTo(1);

    invocationCount.set(0L);
    ClientRequest postRequest = ClientRequest.create(HttpMethod.POST, URI.create("/test")).build();
    StepVerifier.create(filter.filter(postRequest, exchange)).expectError(IllegalStateException.class).verify();
    assertThat(invocationCount.get()).isEqualTo(1);

    invocationCount.set(0L);
    ClientRequest deleteRequest = ClientRequest.create(HttpMethod.DELETE, URI.create("/test")).build();
    StepVerifier.create(filter.filter(deleteRequest, exchange)).expectError(IllegalStateException.class).verify();
    assertThat(invocationCount.get()).isEqualTo(1);
}
 
Example #22
Source File: WingtipsSpringWebfluxExchangeFilterFunction.java    From wingtips with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a subspan (or new trace if no current span exists) to surround the HTTP request, then returns the
 * result of calling {@link #propagateTracingHeadersAndExecute(ClientRequest, ExchangeFunction, TracingState)}
 * to actually execute the request. The whole thing will be wrapped in a {@link
 * WingtipsExchangeFilterFunctionTracingCompletionMonoWrapper} to finish the subspan when the call completes.
 *
 * <p>Span naming and tagging is done here using {@link #tagAndNamingStrategy} and {@link #tagAndNamingAdapter}.
 *
 * @return The result of calling {@link
 * #propagateTracingHeadersAndExecute(ClientRequest, ExchangeFunction, TracingState)} after surrounding the
 * request with a subspan (or new trace if no current span exists).
 */
protected @NotNull Mono<ClientResponse> createAsyncSubSpanAndExecute(
    @NotNull ClientRequest request, @NotNull ExchangeFunction next
) {
    // Handle subspan stuff. Start by getting the current thread's tracing state (so we can restore it before
    //      this method returns).
    TracingState originalThreadInfo = TracingState.getCurrentThreadTracingState();
    TracingState spanAroundCallTracingState = null;

    try {
        // This will start a new trace if necessary, or a subspan if a trace is already in progress.
        Span subspan = Tracer.getInstance().startSpanInCurrentContext(
            getSubspanSpanName(request, tagAndNamingStrategy, tagAndNamingAdapter),
            Span.SpanPurpose.CLIENT
        );

        spanAroundCallTracingState = TracingState.getCurrentThreadTracingState();
        final TracingState spanAroundCallTracingStateFinal = spanAroundCallTracingState;

        // Add request tags to the subspan.
        tagAndNamingStrategy.handleRequestTagging(subspan, request, tagAndNamingAdapter);

        // Execute the request/interceptor chain, wrapped in a WingtipsExchangeFilterFunctionTracingCompletionMonoWrapper
        //      to finish the subspan when the call is done. Also add the tracing state to the Mono Context.
        return new WingtipsExchangeFilterFunctionTracingCompletionMonoWrapper(
            propagateTracingHeadersAndExecute(request, next, spanAroundCallTracingState),
            request,
            spanAroundCallTracingState,
            tagAndNamingStrategy,
            tagAndNamingAdapter
        ).subscriberContext(c -> subscriberContextWithTracingInfo(c, spanAroundCallTracingStateFinal));
    }
    catch(Throwable t) {
        // Something went wrong, probably in the next.exchange(...) chain. Complete the subspan now
        //      (if one exists).
        completeSubspan(spanAroundCallTracingState, request, null, t);

        throw t;
    }
    finally {
        // Reset back to the original tracing state that was on this thread when this method began.
        unlinkTracingFromCurrentThread(originalThreadInfo);
    }
}
 
Example #23
Source File: TracingExchangeFilterFunction.java    From java-spring-web with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ClientResponse> filter(final ClientRequest clientRequest, final ExchangeFunction next) {
	return new TracingClientResponseMono(clientRequest, next, tracer, spanDecorators);
}
 
Example #24
Source File: HttpRequestExecution.java    From charon-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
HttpRequestExecution(String mappingName, ExchangeFunction exchange) {
    this.mappingName = mappingName;
    this.exchange = exchange;
}
 
Example #25
Source File: TestWebClientBuilderConfiguration.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 4 votes vote down vote up
@Bean
public WebClientCustomizer testWebClientCustomizer(ExchangeFunction exchangeFunction) {
	return builder -> builder.exchangeFunction(exchangeFunction);
}
 
Example #26
Source File: TraceWebClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
	return new MonoWebClientTrace(next, request, this);
}
 
Example #27
Source File: TracingExchangeFilterFunction.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ClientResponse> filter(final ClientRequest clientRequest, final ExchangeFunction next) {
  return new TracingClientResponseMono(clientRequest, next, tracer, spanDecorators);
}
 
Example #28
Source File: DeferringLoadBalancerExchangeFilterFunction.java    From spring-cloud-commons with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
	tryResolveDelegate();
	return delegate.filter(request, next);
}
 
Example #29
Source File: WingtipsSpringWebfluxExchangeFilterFunction.java    From wingtips with Apache License 2.0 3 votes vote down vote up
/**
 * Calls {@link #createAsyncSubSpanAndExecute(ClientRequest, ExchangeFunction)} or {@link
 * #propagateTracingHeadersAndExecute(ClientRequest, ExchangeFunction, TracingState)}, depending on whether
 * {@link #surroundCallsWithSubspan} is true or false.
 *
 * <p>NOTE: This method expects the "base tracing state" to be attached to the current thread at the time
 * this method is called. In other words, whatever tracing state is attached to the current thread will be used
 * for generating a subspan (if {@link #surroundCallsWithSubspan} is true) and for propagating the tracing info on
 * the outbound call.
 *
 * @param request The request to use.
 * @param next The next {@link ExchangeFunction} in the chain.
 * @return The result of calling {@link #createAsyncSubSpanAndExecute(ClientRequest, ExchangeFunction)} or
 * {@link #propagateTracingHeadersAndExecute(ClientRequest, ExchangeFunction, TracingState)}, depending on
 * whether {@link #surroundCallsWithSubspan} is true or false.
 */
protected @NotNull Mono<ClientResponse> doFilterForCurrentThreadTracingState(
    @NotNull ClientRequest request, @NotNull ExchangeFunction next
) {
    if (surroundCallsWithSubspan) {
         return createAsyncSubSpanAndExecute(request, next);
    }

    return propagateTracingHeadersAndExecute(request, next, TracingState.getCurrentThreadTracingState());
}
 
Example #30
Source File: InstanceExchangeFilterFunction.java    From spring-boot-admin with Apache License 2.0 votes vote down vote up
Mono<ClientResponse> filter(Instance instance, ClientRequest request, ExchangeFunction next);