com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty Java Examples

The following examples show how to use com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty. 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: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-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 = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(@NonNull Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString((credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #2
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 #3
Source File: LicenseService.java    From spring-microservices-in-action with Apache License 2.0 6 votes vote down vote up
/**
 * Update a license.
 * 
 * @param  license
 *         The license information needs to be updated to.
 */
@HystrixCommand (
		fallbackMethod = "buildFallbackLicenseList",
		threadPoolKey = "licenseByOrgThreadPool",
        threadPoolProperties =
                {@HystrixProperty(name = "coreSize",value="30"),
                 @HystrixProperty(name="maxQueueSize", value="10")},
        commandProperties={         
                 @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="10"),
                 @HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value="75"),
                 @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value="7000"),
                 @HystrixProperty(name="metrics.rollingStats.timeInMilliseconds", value="15000"),
                 @HystrixProperty(name="metrics.rollingStats.numBuckets", value="5")}
)
public void updateLicense(License license){
	licenseRepository.save(license);
}
 
Example #4
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 #5
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 #6
Source File: TokenService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-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 = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString(( credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #7
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 #8
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 -> this.webClient.mutate().baseUrl(address + "/" + id).build().get().retrieve()
          .onStatus(HttpStatus::is4xxClientError, clientResponse ->
              Mono.error(new PlaneNotFoundException(id))
          ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
              Mono.error(new PlaneNotFoundException(id))
          ).bodyToMono(Plane.class));
}
 
Example #9
Source File: TokenService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-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 = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token() {
  val authorizationHeader = Base64Utils.encodeToString((this.clientId + ":" + this.clientSecret).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #10
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", 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 -> this.webClient.mutate().baseUrl(address + "/" + id).build().get().retrieve()
          .onStatus(HttpStatus::is4xxClientError, clientResponse ->
              Mono.error(new PlaneNotFoundException(id))
          ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
              Mono.error(new PlaneNotFoundException(id))
          ).bodyToMono(Plane.class));
}
 
Example #11
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 #12
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-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 = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString((credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #13
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 #14
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 #15
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 #16
Source File: HystrixController.java    From code with Apache License 2.0 6 votes vote down vote up
@GetMapping("/getProductInfoList")
//@HystrixCommand(fallbackMethod = "fallback")
//@HystrixCommand(commandProperties = {
//        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//})
@HystrixCommand(commandProperties = {
        @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
})
//@HystrixCommand
public String getProductInfoList(@RequestParam("number") Integer number) {
    if (number % 2 == 0) {
        return "success";
    }
    RestTemplate restTemplate = new RestTemplate();
    return restTemplate.postForObject("http://localhost:8080/product/listForOrder", Collections.singletonList("157875227953464068"), String.class);
}
 
Example #17
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 #18
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 #19
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-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 = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(@NonNull Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString((credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #20
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 #21
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 #22
Source File: TokenService.java    From Spring-5.0-By-Example with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-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 = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString(( credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #23
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 #24
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 #25
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 #26
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 #27
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 -> this.webClient.mutate().baseUrl(address + "/" + id).build().get().retrieve()
          .onStatus(HttpStatus::is4xxClientError, clientResponse ->
              Mono.error(new PlaneNotFoundException(id))
          ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
              Mono.error(new PlaneNotFoundException(id))
          ).bodyToMono(Plane.class));
}
 
Example #28
Source File: FilmCatalogueClientWithHystrix.java    From hentai-cloudy-rental with Do What The F*ck You Want To Public License 6 votes vote down vote up
@HystrixCommand(
        fallbackMethod = "getFilmByIdFailure",
        //all options here: https://github.com/Netflix/Hystrix/wiki/Configuration
        commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")
        },
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "5"), // the maximum number of HystrixCommands that can execute concurrently. Default 10
            @HystrixProperty(name = "maxQueueSize", value = "101"), //If -1 then SynchronousQueue will be used, otherwise a positive value will be used with LinkedBlockingQueue.
            @HystrixProperty(name = "metrics.healthSnapshot.intervalInMilliseconds", value = "15") //time to wait, between allowing health snapshots to be taken that calculate success and error percentages and affect circuit breaker status.
        })
public Optional<Film> getFilmById(final Long filmId) { //this could return Future or ObservableResult, to use it async, not waste resources, and make it explicit that it takes long
    ResponseEntity<Film> responseEntity = filmCatalogueClient.findOne(filmId);
    if(responseEntity.getStatusCode() != HttpStatus.OK) {
        return Optional.empty();
    }
    return Optional.of(responseEntity.getBody());
}
 
Example #29
Source File: QuoteService.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve one or more quotes.
 *
 * @param symbols comma delimited list of symbols.
 * @return a list of quotes.
 */
@HystrixCommand(fallbackMethod = "getMarkitondemandQuotes",
        commandProperties = {@HystrixProperty(name="execution.timeout.enabled", value="false")})
public List<Quote> getQuotes(String symbols) throws SymbolNotFoundException {
    logger.debug("retrieving quotes for: " + symbols);
    if ( symbols.isEmpty() ) return new ArrayList<>();

    YahooQuoteResponses responses = restTemplate.getForObject(yahoo_url, YahooQuoteResponses.class, symbols, FMT, ENV);
    logger.debug("Got responses: " + responses);
    List<YahooQuote> yahooQuotes = responses.getResults().getQuoteList().getQuote();
    Date createDate = responses.getResults().getCreated();

    List<Quote> quotes = yahooQuotes
            .stream()
            .map(yQuote -> QuoteMapper.INSTANCE.mapFromYahooQuote(yQuote, createDate))
            .collect(Collectors.toList());

    for (Quote quote : quotes) {
        if ( quote.getName() == null ) throw new SymbolNotFoundException( quote.getSymbol() + " not found" );
    }
    return quotes;
}
 
Example #30
Source File: QuoteService.java    From cf-SpringBootTrader with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves an up to date quote for the given symbol.
 * 
 * @param symbols Array of symbols to retrieve quotes for.
 * @return The quote object or null if not found.
 * @throws SymbolNotFoundException
 */
@HystrixCommand(fallbackMethod = "getQuotesFallback",
           commandProperties = {@HystrixProperty(name="execution.timeout.enabled", value="false")})
   @SuppressWarnings("unused")
public List<Quote> getMarkitondemandQuotes(String symbols) throws SymbolNotFoundException {
       List<Quote> result = new ArrayList<>();
       String[] splitSymbols = symbols.split(",");

       for (String symbol : splitSymbols) {
           logger.debug("QuoteService.getQuote: retrieving quote for: " + symbol);
           Map<String, String> params = new HashMap<>();
           params.put("symbol", symbol);

           Quote quote = restTemplate.getForObject(quote_url, Quote.class, params);
           logger.debug("QuoteService.getQuote: retrieved quote: " + quote);
           result.add(quote);

           if (quote.getSymbol() == null) {
               throw new SymbolNotFoundException("Symbol not found: " + symbol);
           }
       }

	return result;
}