Toby의 ReactiveProgramming 11

Spring 6의 새로운 HTTP Interface와 3가지 REST Clients

RestTemplate @SpringBootApplication public class RestApplication { @Bean public ApplicationRunner init(ErApi api) { return args -> { //https://open.er-api.com/v6/latest RestTemplate rt = new RestTemplate(); /* String res = rt.getForObject("https://open.er-api.com/v6/latest", String.class); System.out.println(res); */ Map res = rt.getForObject("https://open.er-api.com/v6/latest", Map.class); Syst..

Flux의 특징과 활용방법

여러 개의 Reactive 스타일로 받는 Flux @Slf4j @SpringBootApplication public class Chapter14Application { @RestController public static class MyController { @GetMapping("/event/{id}") public Mono event(@PathVariable long id) { return Mono.just(new Event(id, "event " + id));//특정 오브젝트를 컬렉션으로 다뤄 리액티브 스타일로 다루고 싶다면 어떻게 할까? } @GetMapping("/events") public Flux events() { return Flux.just(new Event(1L, "event1"), ..

Mono의 동작방식과 block()

@SpringBootApplication public class Chapter13Application { public static void main(String[] args) { //Tomcat을 기본으로 사용하는 것이 아닌, netty가 실행이된다. //비동기 non-blocking 에 사용되는 서버인 netty가 기본적으로 실행되는 것을 확인 할 수 있다. SpringApplication.run(Chapter13Application.class, args); } } dependency를 추가할 때는 spring-web과 spring-webflux를 같이 import 하지 말자(webflux에 web을 포함하고 있음) 기본적으로 spring-webflux의 dependency만 있다면, 서버는 톰캣이 아..

WebFlux

이전에 사용했던 AsyncRestTemplate의 getForEntity 메서드 같은 경우, Http 요청을 모두 받기 때문에 Http Header, 상태 코드 모두 돌아오기 때문에 좋지 않다. Mono @GetMapping("/rest") public Mono rest(int idx) { //Mono를 사용하면, 어떤 오브젝트든 받아서 반환할 수 있다. //Mono를 컨테이너(컬렉션)이라고, 생각하면 된다 -> 컨테이너 = Optional, List 등과 같이 컨테이너로 데이터를 감싸면 여러 기능을 쓸 수 있다. //Mono m = Mono.just("Hello");//일반 String 메서드와 달리 Mono로 감싸게 되면, 많은 기능을 쓸 수 있는것을 볼 수 있다 return Mono.just("He..

CompletableFuture

CompletableFuture : 비동기 작업을 간단하게 완료하는 작업을 할 수 있다. public static void main(String[] args) throws ExecutionException, InterruptedException { //CompletableFuture cf = CompletableFuture.completedFuture(1); //비동기 작업을 간단하게 완료하는 작업을 할 수 있다. CompletableFuture cf = new CompletableFuture(); //값을 넘기지 않았기 때문에 무한정 대기 //cf.complete(2);//값을 넣어준다 cf.completeExceptionally(new RuntimeException()); //예외가 발생했다는것을 알..

AsyncRestTemplate의 콜백 헬과 중복 작업 문제

Refectoring: CallBack 지옥에서 벗어나는 코드 Version 1 코드를 자세히 보면, 결과를 리턴으로 받는 것이 아닌 콜백 형식으로 받게 되니, Callback 지옥이 발생하게 된다. 에러를 처리해주는 코드가 매번 중복되는 문제도 계속 발생한다. @SpringBootApplication public class Chapter10Application { @RestController public static class MyController { public static final String URL1 = "http://localhost:8081/service1?req={req}"; public static final String URL2 = "http://localhost:8081/servic..

비동기 RestTemplate과 비동기 MVC/Servlet

Thread Pool Hell(스레드 풀 지옥) LinkedIn의 Thread Pool 2~4시 사이에 요청이 급격히 많아졌고, 그에 따라 Latency도 급격히 증가한 것을 볼 수 있다 Thread요청이 급격히 늘어나 Queue에 대기하고 있던 요청들도 늘게 되어, Latency가 길어진 것을 볼 수 있다. 왜 이렇게 Latency가 늘어났을까? 최신 BackEnd 구조를 보면, 외부 API 호출을 통한 요청으로 서로 간 통신을 한다 외부 API 호출을 통한 요청은 I/O 요청으로 Blocking 처리가 되고, 스레드가 Blocking 상태가 되어 놀고 있기 때문에 Latancy가 증가한 것이다. 스레드를 늘리는것은 근본적인 해결이 될 수 없다(스레드 개수를 늘리는 것은 한정되어 있으며, 오히려 잦은 ..

자바와 스프링의 비동기 기술

JAVA에서의 비동기 작업(Future) JVM의 Future란? JVM 1.5에서 나왔다, 비동기적인 연산,작업에 대한 결과를 가지고 있는 인터페이스 public static void main(String[] args) throws InterruptedException { ExecutorService es = Executors.newCachedThreadPool(); Thread.sleep(2000); System.out.println("Hello"); //2초 후 해당 결과가 실행되고 Exit 실행 System.out.println("Exit"); } 2초 뒤에 Hello가 출력되고, Exit가 출력된다 동기적 실행이 된다. 비동기적 실행 public static void main(String[] a..

Reactive Streams - Operators

Stream과 같이 데이터를 Operator(연산)을 통해 가공하여 Subscriber에 전달할 수 있다. 초기 /** * Reactive Streams - Operators * Publisher -> [Data1] -> Operator -> [Data2] -> Subscriber * Operator 연산을 통하면서 데이터가 가공되서 Subscriber에 제공이 된다. */ @Slf4j public class PubSub { public static void main(String[] args) { Publisher pub = iterPub(Stream.iterate(1, a -> a + 1).limit(10).collect(Collectors.toList())); pub.subscribe(logSub()..