Spring WebFlux.

배경

  • 어느 순간 비동기가 유행하게 되고 살아남기 위해서는 유행을 쫓아 가야 합니다.[뇌피셜]
  • Servlet 3.1 부터 비동기 지원.
  • 비동기가 유행 이더라.
  • 함수형 언어가 유행이더라.
  • 비동기 + 함수형언어 + java + spring = WebFlux

Performance

  • 더 빨라지지 않는다.
  • 적은 수의 thread 와 메모리를 사용하기 때문에 예측 가능하게 확장 할 수 있다.

Reactive

  • reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change Wiki
  • 선언적이고 데이터 스트림을 사용해 변화가 전파 되는대 관심을 둔 프로그래임 패러다임.
b = 1
c = 1
a = b + c
b = 2
print(a)
//imperactive => 2
//reactive =>3

Reactive stream

  • 데이터의 스트림 표현 방식 규약 ReativeGit
  • 비동기 스트림의로 데이터를 추상화 하면 가장 큰 문제는 consumer 가 producer 의 속도를 따라오지 못할때 발생
  • consumer 가 producer 의 속도를 조절 할 수 있음
Definition
  • process a potentially unbounded number of elements
  • in sequence,
  • asynchronously passing elements between components,
  • with mandatory non-blocking backpressure.

None-blocking

  • asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the transmission has finished.
  • non-blocking web stack to handle concurrency with a small number of threads and scale with fewer hardware resources

Functional

  • Treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions or declarations

WebFlux

  • None-blocking
  • Reactive (stream)
  • Functional
  • Spring

Sequece flow

sequenceDiagram User ->>+ EventLoop : GET /person/1 EventLoop ->> DispatherHandler : server thread DispatherHandler ->> WebHandler : handler::getPerson(req) WebHandler ->> Service : getPersonName(id) Service ->> DB : select id from person where.. DB -->> EventLoop : return server thread EventLoop ->> DB : server thread DB -->> Service : record Service -->> WebHandler : 1 WebHandler -->> DispatherHandler : resposne.body(1) DispatherHandler -->> EventLoop : resposne.body(1) EventLoop -->>- User : response.body(1)

Async Servlet 3.1+

  1. Client sends a request
  2. Servlet container allocates a thread and invokes a servlet in it
  3. The servlet calls request.startAsync(), saves the AsyncContext, and returns
  4. The container thread is exited all the way but the response remains open
  5. Some other thread uses the saved AsyncContext to complete the response
  6. Client receives the response

Concurrency Model (thread model)

WebFlux