programing

Java의 Mono 클래스: 무엇을 언제 사용할 수 있습니까?

sourcejob 2023. 2. 28. 23:26
반응형

Java의 Mono 클래스: 무엇을 언제 사용할 수 있습니까?

다음 코드가 있습니다.

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
public class GreetingHandler 
    public Mono<ServerResponse> hello(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
        .body(BodyInserters.fromValue("Hello Spring!"));
    }
}

이 코드는 Mono 클래스의 기능과 기능을 제외하고 이해했습니다.많이 검색했지만, 단도직입적으로 「Mono」의 클래스는 무엇이며, 그것을 언제 사용하는가」라고 하는 요점이 되지 않았습니다.

A Mono<T>전문화Publisher<T>최대 1개의 아이템을 방출한 후 (옵션으로) 종료한다.onComplete신호 또는 신호onError신호.이 명령어는 이 명령어에 사용할 수 있는 연산자의 서브셋만 제공합니다.Flux, 및 일부 연산자(를 조합한 연산자 제외)Mono다른 사람과 함께Publisher)로 전환합니다.Flux.예를들면,Mono#concatWith(Publisher)a를 반환하다Flux하는 동안에Mono#then(Mono)다른 것을 반환하다Mono. 를 사용할 수 있습니다.Mono완료 개념만 있는 값 없는 비동기 프로세스를 나타냅니다(Runnable과 유사).작성하려면 , 빈칸을 사용합니다.Mono<Void>.

모노 및 플럭스는 모두 반응성 스트림입니다.그들은 표현하는 것이 다르다.모노는 0~1 원소의 스트림이며 플럭스는 0~N 원소의 스트림입니다.

이 두 스트림의 의미론 차이는 매우 유용합니다.예를 들어 Http 서버에 대한 요구가0 또는 1의 응답을 수신할 것으로 예상되는 경우 이 경우 플럭스를 사용하는 것은 부적절합니다.반대로, 어떤 구간에서 수학 함수의 결과를 계산하면 그 구간에서 숫자당 하나의 결과가 나올 것으로 예상한다.이 경우 플럭스를 사용하는 것이 적절합니다.

사용방법:

Mono.just("Hello World !").subscribe(
  successValue -> System.out.println(successValue),
  error -> System.err.println(error.getMessage()),
  () -> System.out.println("Mono consumed.")
);
// This will display in the console :
// Hello World !
// Mono consumed.

// In case of error, it would have displayed : 
// **the error message**
// Mono consumed.

Flux.range(1, 5).subscribe(
  successValue -> System.out.println(successValue),
  error -> System.err.println(error.getMessage()),
  () -> System.out.println("Flux consumed.")
);
// This will display in the console :
// 1
// 2
// 3
// 4
// 5
// Flux consumed.

// Now imagine that when manipulating the values in the Flux, an exception
// is thrown for the value 4. 
// The result in the console would be :
// An error as occurred
// 1
// 2
// 3
//
// As you can notice, the "Flux consumed." doesn't display because the Flux
// hasn't been fully consumed. This is because the stream stop handling future values
// if an error occurs. Also, the error is handled before the successful values.

출처:Reactor Java #1 - 모노 및 플럭스 작성 방법, 모노, 비동기 0-1 결과

도움이 될 수 있습니다.모노 문서

언급URL : https://stackoverflow.com/questions/60705382/mono-class-in-java-what-is-and-when-to-use

반응형