20 August 2019

Spring MVC AsyncRestTemplate

Simple example to call Async RestTemplate :

https://github.com/devwebcl/async-springmvc-poc

Most important snippet code:

public AsyncRestTemplate asyncRestTemplateFactory() {
 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

 connManager.setMaxTotal(maxTotalConnections);
 connManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
 CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
 HttpComponentsAsyncClientHttpRequestFactory requestAsyncFactory =
 new HttpComponentsAsyncClientHttpRequestFactory();
 requestAsyncFactory.setConnectionRequestTimeout(connectRequestTimeout);
 requestAsyncFactory.setConnectTimeout(connectTimeout);
 requestAsyncFactory.setReadTimeout(readTimeout);
 requestAsyncFactory.setHttpClient(httpClient);

 AsyncRestTemplate art = new AsyncRestTemplate();
 art.setAsyncRequestFactory(requestAsyncFactory);


 //deberia ser inyectado desde DI container
 return new AsyncRestTemplate(requestAsyncFactory);
 }



and



public String callback() throws Exception {

        Map<String, ListenableFuture<ResponseEntity<String>>> futures = new HashMap<>(); //podria ser un Guava Table
        List<String> respuestas = new ArrayList<>();
       

        AsyncFactory af = new AsyncFactory();
        AsyncRestTemplate artf = af.asyncRestTemplateFactory();

        //url a visitar
        String[] url = {"http://google.com", "http://bing.com", "https://stackoverflow.com/", "https://www.infoq.com/", "https://dzone.com/",
                        "https://jakarta.ee/", "https://www.eclipse.org/",  "http://www.noexisto.cl/", "https://spring.io/", "https://github.com/",
                        "https://www.apache.org/"};

       
        //agrego llamadas asincronas
        for(int i=0; i<url.length; i++) {
           
            HttpMethod method = HttpMethod.GET;
            Class<String> responseType = String.class;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            HttpEntity<String> requestEntity = new HttpEntity<>("params", headers);
            //la llave es la misma url (modificable)
           
            // usar DeferredResult ?
            ListenableFuture<ResponseEntity<String>> future = artf.exchange(url[i], method, requestEntity, responseType);
                   

            // es "opcional"
            future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
                  @Override
                  public void onSuccess(ResponseEntity<String> result) {
                    System.out.println("onSuccess " + result.getHeaders() );
                    //TODO: DeferredResult ?
                  }

                  @Override
                  public void onFailure(Throwable ex) {
                    System.out.println("onFailure!!! " + ex );
                  }
                });
               
             futures.put(url[i], future);
        }

       
        //TODO: borrar !
        // duermo los hilos solo por prueba:
        int segundos_sleep = 2;
        System.out.println("durmiendo por " + segundos_sleep + " segundos...");
        Thread.sleep(segundos_sleep * 1000);

       
        int i=0;
        //voy uno a uno... con Guava SuccessfulAsList seria lo mismo al final ya que quiero cada uno de los responses
        for (Map.Entry<String, ListenableFuture<ResponseEntity<String>>> llave : futures.entrySet()) {
           
            System.out.println((++i)+". -----------------------------------------------------\n");

            System.out.println("key = " + llave.getKey() + ",\n value = " + llave.getValue());
   
            ListenableFuture<ResponseEntity<String>> future = llave.getValue();
            ResponseEntity<String> entity = null;

            try {
           
            entity = future.get(); // blocking en cada uno, pero la respuesta ya puede existir
            } catch (InterruptedException ie) {
                ie.printStackTrace();
                continue;
            } catch (ExecutionException ee) {
                ee.printStackTrace();
                continue;
            }
               
           
            String headers = entity.getHeaders().toString();
           
            if(headers.indexOf("domain=")!=-1)
                System.out.println(headers.substring(headers.indexOf("; domain=")));
            else                
                System.out.println(headers);

            System.out.println(entity.getStatusCode());
            //System.out.println(entity.getBody());
            respuestas.add(entity.getBody().toString());
           
            System.out.println("isDone? " + future.isDone() + "\n");
        }
          

       
        System.out.println("\nfin.");
   

        //return respuestas;
        return "done";
    }

  


No comments :

My Blog List

Blog Archive

Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.