如何使用java8和rxjava组合Hystrix可观察对象



我有两个api调用。它们都被Hystrix包裹:

这里有一个例子:

@HystrixCommand()
    public Observable<String> getAvailableFlightBookings() {
        return new ObservableResult<String>() {
            @Override
            public String invoke() {
                URI uri = registryService.getServiceUrl("flight-booking-service", "http://localhost:8081/flight-booking-service");
                String url = uri.toString() + "/flights/list";
                ResponseEntity<String> resultStr = restTemplate.getForEntity(url, String.class);
                return resultStr.getBody();
            }
        };
    }

我有以下代码,我正在努力完成:

public DeferredResult<FlightDetails> getAllFlightDetails() {
        //Calling previous defined functions
        Observable<String> availableFlightBookings=flightBookingIntegrationService.getAvailableFlightBookings();
        Observable<String> couponId=couponIntegrationService.getCoupon();

        Observable<String> details = Observable.zip(
    ..?

    }

我不确定如何调用以下API:

flightBookingIntegrationService.getAvailableFlightBookings();
couponIntegrationService.getCoupon();

并使用Observable.zip

填充最终结果对象(FlightDetails)

FlightDetails:

public class FlightDetails {
    String couponId;
    String availableFlightList;
..
}

谢谢你,射线。

我不熟悉Hystrix,但是压缩两个可观察对象应该与纯RxJava没有什么不同。

Observable.zip(availableFlightBookings, couponId, new Func2<String, String, FlightDetails>() {
    @Override
    public FlightDetails call(String availableFlights, String coupon) {
        return new FlightDetails(availableFlights, coupon);
    }
}).subscribe();

首先使您的Hystrix命令类为@Component,因为您正在使用Spring,然后将其Autowire放入控制器并调用

使用lambdas,将看起来像这样:

public DeferredResult<FlightDetails> getAllFlightDetails() {
    Observable<String> availableFlightBookings=flightBookingIntegrationService.getAvailableFlightBookings();
    Observable<String> couponId=couponIntegrationService.getCoupon();
    //Create a new DeferredResult
    DeferredResult<FlightDetails> result = new DeferredResult();
    Observable.zip(availableFlightBookings,couponId, (avaliable, coupon) -> {
     // do some logic here or just..
    return new FlightDetails(avaliable,coupon);
    }).subscribe(result::setResult,result::setErrorResult);
    return result;
}

相关内容

  • 没有找到相关文章

最新更新