org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec Java Examples

The following examples show how to use org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec. 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: PlaneService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "plane-by-id",groupKey = "airline-flights",fallbackMethod = "fallback",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Plane> plane(String id) {
  return discoveryService.serviceAddressFor(this.planesService).next()
          .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/" + id).build().get()))
          .flatMap(requestHeadersUriSpec ->
            Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token()),(reqSpec, token) ->{
              reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
            })
           .next())
          .map(RequestHeadersSpec::retrieve)
          .flatMap(eq -> eq.bodyToMono(Plane.class));
}
 
Example #2
Source File: FlightService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "available-seats-query",groupKey = "airline-flights-query",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AvailableSeats> availableSeats(@NonNull String flightId){
  return discoveryService.serviceAddressFor(this.flightsService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address +"/" + flightId+ "/available").build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.flightsCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(res -> res.bodyToMono(AvailableSeats.class));
}
 
Example #3
Source File: FlightService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "flight-query",groupKey = "airline-flights-query",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Flux<Flight> search(@NonNull FlightSearch query){
  return discoveryService.serviceAddressFor(this.flightsService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address + "/query").build().post().body(
              BodyInserters.fromObject(query))))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.flightsCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMapMany(res -> res.bodyToFlux(Flight.class));
}
 
Example #4
Source File: PassengerService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "create-passenger",groupKey = "ecommerce-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Passenger> newPassenger(@NonNull PassengerRequest passengerRequest){
  return discoveryService.serviceAddressFor(this.passengersService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address).build().post().body(BodyInserters.fromObject(passengerRequest))))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.passengersCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(res -> res.bodyToMono(Passenger.class));
}
 
Example #5
Source File: BookingService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "buy-tickets",groupKey = "ecommerce-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Passenger> buyTicket(@NonNull BookingRequest bookingRequest){
  return discoveryService.serviceAddressFor(this.bookingsService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address).build().post().body(BodyInserters.fromObject(bookingRequest))))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.bookingsCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(res -> res.bodyToMono(Passenger.class));
}
 
Example #6
Source File: FlightService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "flight-by-id",groupKey = "airline-fare",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Flight> flight(String id) {
  return discoveryService.serviceAddressFor(this.flightService).next()
      .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/" + id).build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.credentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
       .next())
      .map(RequestHeadersSpec::retrieve)
      .doOnError(e -> {throw new RuntimeException("Invalid flight");})
      .flatMap(eq -> eq.bodyToMono(Flight.class));
}
 
Example #7
Source File: BookingService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "bookings-by-flight-id",groupKey = "airline-fare",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Set<Booking>> bookingOfFlight(String flightId) {
  return discoveryService.serviceAddressFor(this.bookingService).next()
      .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/flight/" + flightId).build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.credentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(eq -> {
        ParameterizedTypeReference<Set<Booking>> typeRef = new ParameterizedTypeReference<Set<Booking>>() {};
        return eq.bodyToMono(typeRef);
      });
}
 
Example #8
Source File: PlaneService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "plane-by-id",groupKey = "airline-flights",fallbackMethod = "fallback",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Plane> plane(String id) {
  return discoveryService.serviceAddressFor(this.planesService).next()
          .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/" + id).build().get()))
          .flatMap(requestHeadersUriSpec ->
            Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.credentials)),(reqSpec, token) ->{
              reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
            })
           .next())
          .map(RequestHeadersSpec::retrieve)
          .flatMap(eq -> eq.bodyToMono(Plane.class));
}
 
Example #9
Source File: BookingService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "available-seats", groupKey = "airline-flights", commandProperties = {
    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<TotalBooked> totalBooked(String flightId) {
  return discoveryService.serviceAddressFor(this.bookingsService).next()
      .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/flights" + flightId).build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.credentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
          .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(eq -> eq.bodyToMono(TotalBooked.class));
}
 
Example #10
Source File: PlaneService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "plane-by-id", groupKey = "airline-booking", commandProperties = {
    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Plane> plane(String id) {
  return discoveryService.serviceAddressFor(this.planesService).next()
      .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/" + id).build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.credentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(eq -> eq.bodyToMono(Plane.class));
}
 
Example #11
Source File: FlightService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "flight-by-id",groupKey = "airline-fare",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Flight> flight(String id) {
  return discoveryService.serviceAddressFor(this.flightService).next()
      .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/" + id).build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.credentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
       .next())
      .map(RequestHeadersSpec::retrieve)
      .doOnError(e -> {throw new RuntimeException("Invalid flight");})
      .flatMap(eq -> eq.bodyToMono(Flight.class));
}
 
Example #12
Source File: FareService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "fare-by-id",groupKey = "airline-booking",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<Fare> fare(String id){
  return discoveryService.serviceAddressFor(this.fareService).next()
      .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/" + id).build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.credentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(eq -> eq.bodyToMono(Fare.class));
}
 
Example #13
Source File: FlightService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "available-seats-query",groupKey = "airline-flights-query",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AvailableSeats> availableSeats(@NonNull String flightId){
  return discoveryService.serviceAddressFor(this.flightsService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address +"/" + flightId+ "/available").build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.flightsCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(res -> res.bodyToMono(AvailableSeats.class));
}
 
Example #14
Source File: FlightService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "flight-query",groupKey = "airline-flights-query",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Flux<Flight> search(@NonNull FlightSearch query){
  return discoveryService.serviceAddressFor(this.flightsService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address + "/query").build().post().body(
              BodyInserters.fromObject(query))))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.flightsCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMapMany(res -> res.bodyToFlux(Flight.class));
}
 
Example #15
Source File: BookingService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "bookings-total",groupKey = "airline-bookings-total",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<TotalBooked> totalBooked(@NonNull String flightId){
  return discoveryService.serviceAddressFor(this.bookingsService).next()
      .flatMap(address -> Mono
          .just(this.webClient.mutate().baseUrl(address + "/" + flightId +"/total").build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token(this.bookingsCredentials)),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
              .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(res -> res.bodyToMono(TotalBooked.class));
}
 
Example #16
Source File: BookingService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "available-seats", groupKey = "airline-flights", commandProperties = {
    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "800"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<TotalBooked> totalBooked(String flightId) {
  return discoveryService.serviceAddressFor(this.bookingsService).next()
      .flatMap(address -> Mono.just(this.webClient.mutate().baseUrl(address + "/flights" + flightId).build().get()))
      .flatMap(requestHeadersUriSpec ->
          Flux.combineLatest(Flux.just(requestHeadersUriSpec),Flux.from(tokenService.token()),(reqSpec, token) ->{
            reqSpec.header("Authorization","Bearer" + token.getToken());
            return reqSpec;
          })
          .next())
      .map(RequestHeadersSpec::retrieve)
      .flatMap(eq -> eq.bodyToMono(TotalBooked.class));
}
 
Example #17
Source File: ApiProxyController.java    From demo-spring-webflux-api-gateway with Apache License 2.0 4 votes vote down vote up
/**
    * 
    * @param exchange 
    * @return
    */
   @RequestMapping("/**")
   public Mono<Void>  proxyRequest(ServerWebExchange exchange)
{
	ServerHttpRequest frontEndReq = exchange.getRequest();
	ServerHttpResponse frontEndResp = exchange.getResponse();
	String path = frontEndReq.getPath().pathWithinApplication().value();
	HttpMethod httpMethod = frontEndReq.getMethod();
	RequestBodySpec reqBodySpec = webClient.method(httpMethod).
			uri(backendServiceUrlPrefix.concat(path)).
			headers(httpHeaders -> 
			        {
	                  httpHeaders.addAll(frontEndReq.getHeaders());
	                  httpHeaders.remove("HOST");
	                });
	
	RequestHeadersSpec<?> reqHeadersSpec;
    if (requireHttpBody(httpMethod)) {
    		  reqHeadersSpec = reqBodySpec.body(BodyInserters.fromDataBuffers(frontEndReq.getBody()));
    } else {
    	      reqHeadersSpec = reqBodySpec;
    	}
    
	//调用后端服务
	return reqHeadersSpec.exchange().timeout(Duration.ofMillis(backendServiceTimeoutInMillis)).
			onErrorResume(ex -> 
		    { 
			    //调用后端服务异常(超时、网络问题)时,转发到后端异常-后控制器
		    	    //此处也可不用转发,用frontEndResp.writeWith(...)直接将异常响应写回给调用方
		    	    Map<String,Object> forwardAttrs = new HashMap<>();
		    	    forwardAttrs.put(Constant.BACKEND_EXCEPTION_ATTR_NAME,ex);
                return WebfluxForwardingUtil.forward(Constant.BACKEND_EXCEPTION_PATH,exchange,forwardAttrs)
                		.then(Mono.empty());
			}).flatMap(backendResponse -> 
		    {
		    	    //将后端服务的响应回写到前端resp
		    	    frontEndResp.setStatusCode(backendResponse.statusCode());
		    	    frontEndResp.getHeaders().putAll(backendResponse.headers().asHttpHeaders());
		    	    return frontEndResp.writeWith(backendResponse.bodyToFlux(DataBuffer.class));
		    	}
		    	);
}
 
Example #18
Source File: WebClientHttpRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

	String scheme = requestUrl.getScheme();
	if (isAlreadyRouted(exchange)
			|| (!"http".equals(scheme) && !"https".equals(scheme))) {
		return chain.filter(exchange);
	}
	setAlreadyRouted(exchange);

	ServerHttpRequest request = exchange.getRequest();

	HttpMethod method = request.getMethod();

	HttpHeaders filteredHeaders = filterRequest(getHeadersFilters(), exchange);

	boolean preserveHost = exchange
			.getAttributeOrDefault(PRESERVE_HOST_HEADER_ATTRIBUTE, false);

	RequestBodySpec bodySpec = this.webClient.method(method).uri(requestUrl)
			.headers(httpHeaders -> {
				httpHeaders.addAll(filteredHeaders);
				// TODO: can this support preserviceHostHeader?
				if (!preserveHost) {
					httpHeaders.remove(HttpHeaders.HOST);
				}
			});

	RequestHeadersSpec<?> headersSpec;
	if (requiresBody(method)) {
		headersSpec = bodySpec.body(BodyInserters.fromDataBuffers(request.getBody()));
	}
	else {
		headersSpec = bodySpec;
	}

	return headersSpec.exchange()
			// .log("webClient route")
			.flatMap(res -> {
				ServerHttpResponse response = exchange.getResponse();
				response.getHeaders().putAll(res.headers().asHttpHeaders());
				response.setStatusCode(res.statusCode());
				// Defer committing the response until all route filters have run
				// Put client response as ServerWebExchange attribute and write
				// response later NettyWriteResponseFilter
				exchange.getAttributes().put(CLIENT_RESPONSE_ATTR, res);
				return chain.filter(exchange);
			});
}