如何使用java8和rxjava组成Hystrix observable

时间:2015-07-13 14:25:50

标签: rx-java hystrix

我有两个api要调用。他们都用Hystrix Observable包裹着:

这里有一个例如:

@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;

..
}

谢谢你, 射线。

2 个答案:

答案 0 :(得分:1)

我不熟悉Hystrix,但是压缩两个observable不应该与纯RxJava不同。

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

答案 1 :(得分:1)

首先让你的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;
}