출처 : 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

,

특정 테이블에 10GB 데이터가 있는 경우

 

TEMP 함수로 SWAP과 같이 변환

 

1] A_TABLE -> A_TABLE_TEMP로  3개월치 데이터 

   insert into   select

 

2] A_TABLE  -> A_TABLE_BACK 테이블 이름 변경  

 

3] A_TABLE_TEMP -> A  테이블 이름 변경

 

4] A_TABLE_BACK  새로운  Database로 이관

 

 

유저가 과거 자료를 원하는 경우 4에서 데이터 추출하여 알림

 

'' 카테고리의 다른 글

ubuntu nginx php mysql 구축  (0) 2021.03.03
라디오 버튼 제이쿼리  (0) 2020.08.24
GS인증(보안성)  (7) 2020.04.13
express + morgan  (0) 2019.04.01
promise  (0) 2019.03.28
블로그 이미지

iesay

,

nodemon 설정 방법

nodejs 2020. 12. 9. 16:19

app.js 


var express = require('express');

var app = express();

var logger = require('morgan');


// router 설정

var indexRouter = require('./routes/index');


app.use(logger('dev'));

app.use(express.json());

app.use(express.urlencoded({ extended: false }));


// view 경로 설정

app.set('views', __dirname + '/views');


// 화면 engine을 html로 설정

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);


// port setup

app.set('port', process.env.PORT || 3000);



// 기본 path를 /public으로 설정(css, javascript 등의 파일 사용을 위해)

app.use(express.static(__dirname + '/public'));


app.use('/', indexRouter);


module.exports = app;


var server = app.listen(app.get('port'), function() {

    console.log('Express server listening on port ' + server.address().port);

  });

 



노드몬 설치 후 실행 된다.

 #nodemon app.js


'nodejs' 카테고리의 다른 글

nodejs so파일  (0) 2021.09.10
MongoError: Cannot use a session that has ended  (0) 2021.07.20
nodejs 버전 업데이트 하기  (0) 2021.07.15
axios 전송  (0) 2020.12.08
web3.js 비동기 nodejs 함수 비교  (0) 2020.11.24
블로그 이미지

iesay

,