How to use AsyncRestTemplate to make multiple calls simultaneously?

前端 未结 6 2040
耶瑟儿~
耶瑟儿~ 2021-02-18 22:42

I don\'t understand how to use AsyncRestTemplate effectively for making external service calls. For the code below:

class Foo {

    public void doS         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-18 23:11

    If you don't have to use 'AsyncRestTemplate' I would suggest to use RxJava instead. RxJava zip operator is what you are looking for. Check code below:

    private rx.Observable externalCall(String url, int delayMilliseconds) {
        return rx.Observable.create(
                subscriber -> {
                    try {
                        Thread.sleep(delayMilliseconds); //simulate long operation
                        subscriber.onNext("response(" + url + ") ");
                        subscriber.onCompleted();
                    } catch (InterruptedException e) {
                        subscriber.onError(e);
                    }
                }
        );
    }
    
    public void callServices() {
        rx.Observable call1 = externalCall("url1", 1000).subscribeOn(Schedulers.newThread());
        rx.Observable call2 = externalCall("url2", 4000).subscribeOn(Schedulers.newThread());
        rx.Observable call3 = externalCall("url3", 5000).subscribeOn(Schedulers.newThread());
        rx.Observable.zip(call1, call2, call3, (resp1, resp2, resp3) -> resp1 + resp2 + resp3)
                .subscribeOn(Schedulers.newThread())
                .subscribe(response -> System.out.println("done with: " + response));
    }
    

    All requests to external services will be executed in separate threads, when last call will be finished transformation function( in example simple string concatenation) will be applied and result (concatenated string) will be emmited from 'zip' observable.

提交回复
热议问题