출처 : http://wonwoo.ml/index.php/post/903

 

nodejs에서 비동기 개발 경험 있는데

webflux를 쓰지 않고 비동기를 사용해야 될일이 생겼다.

 

부하가 아주 많은 서비스중인 대상이 외부 API 인터페이스 통신하는데

10건중 2건 정도 간혈적으로 오류가 뜬다

그래서 response 가 없으면 한번 더 요청하는 로직을 추가 해도 이모양이다.

 

그래서 자바에 비동기를 부분적으로 사용할수 있다는걸 듣고

적용 하였다.

 

소스

 package com.mattjtodd.asyncresttemplateexample;

import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

@SpringBootApplication
public class AsyncRestTemplateExampleApplication {
 static AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
  
 
    public static void main(String[] args) throws InterruptedException, ExecutionException {
     asyncRestTemplateTest();
    }
   
   
    public static void asyncRestTemplateTest() throws InterruptedException, ExecutionException {
        ListenableFuture<ResponseEntity<Map>> entity = asyncRestTemplate.getForEntity("https://api.exchangeratesapi.io/latest?base=USD", Map.class);
        entity.addCallback(result -> {
            System.out.println(result.getStatusCode());
            System.out.println("body:          "+ result.getBody().toString());
        }, ex -> System.out.println(ex.getStackTrace()));

        System.out.println("asyncRestTemplateTest:             "+ Map.class);
        TimeUnit.SECONDS.sleep(8);
    }  
}

 

 

결과

16:58:20.514 [main] DEBUG org.springframework.web.client.AsyncRestTemplate - Created asynchronous GET request for "https://api.exchangeratesapi.io/latest?base=USD"
16:58:20.527 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]
asyncRestTemplateTest:             interface java.util.Map
16:58:21.123 [SimpleAsyncTaskExecutor-1] DEBUG org.springframework.web.client.AsyncRestTemplate - Async GET request for "https://api.exchangeratesapi.io/latest?base=USD" resulted in 200 (OK)
16:58:21.124 [SimpleAsyncTaskExecutor-1] DEBUG org.springframework.web.client.RestTemplate - Reading [interface java.util.Map] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@732136b8]
200
body:          {rates={CAD=1.2775883576, HKD=7.7520997921, ISK=128.6486486486, PHP=48.1022869023, DKK=6.1841995842, HUF=297.9875259875, CZK=21.4045738046, GBP=0.7304199584, RON=4.0538877339, SEK=8.4114760915, IDR=14034.3534303534, INR=72.9513513514, BRL=5.4016632017, RUB=74.3491891892, HRK=6.2854885655, JPY=105.5883575884, THB=30.0191268191, CHF=0.9016216216, EUR=0.8316008316, MYR=4.0655301455, BGN=1.6264449064, TRY=7.0942203742, CNY=6.4547193347, NOK=8.5426195426, NZD=1.3920997921, ZAR=14.943950104, USD=1.0, MXN=20.2120582121, SGD=1.3361330561, AUD=1.305031185, ILS=3.2837422037, KRW=1120.8066528067, PLN=3.7275675676}, base=USD, date=2021-02-08}
 

 

'자바(Spring)' 카테고리의 다른 글

ajax 통신  (0) 2020.09.06
JSON 파일 파싱 스프링 java VO저장  (0) 2020.08.29
블로그 이미지

iesay

,