當前位置: 首頁>>代碼示例>>Java>>正文


Java Mono類代碼示例

本文整理匯總了Java中reactor.core.publisher.Mono的典型用法代碼示例。如果您正苦於以下問題:Java Mono類的具體用法?Java Mono怎麽用?Java Mono使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Mono類屬於reactor.core.publisher包,在下文中一共展示了Mono類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: requestPressure

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Override
public Mono<NumberProto.Number> requestPressure(Flux<NumberProto.Number> request) {
    if (explicitCancel.get()) {
        // Process a very long sequence
        Disposable subscription = request.subscribe(n -> System.out.println("S: " + n.getNumber(0)));
        return Mono
                .just(protoNum(-1))
                .delayElement(Duration.ofMillis(250))
                // Explicitly cancel by disposing the subscription
                .doOnSuccess(x -> subscription.dispose());
    } else {
        // Process some of a very long sequence and cancel implicitly with a take(10)
        return request.map(req -> req.getNumber(0))
                .doOnNext(System.out::println)
                .take(10)
                .last(-1)
                .map(CancellationPropagationIntegrationTest::protoNum);
    }
}
 
開發者ID:salesforce,項目名稱:reactive-grpc,代碼行數:20,代碼來源:CancellationPropagationIntegrationTest.java

示例2: callSSOProvider

import reactor.core.publisher.Mono; //導入依賴的package包/類
public Mono<User> callSSOProvider(String accessToken, SSOProvider ssoProvider) {
    SSOProperties.SSOValues keys = ssoProperties.getProviders().get(ssoProvider);
    return WebClient.builder()
            .build()
            .get()
            .uri(keys.getProfileUrl())
            .header(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " " + accessToken)
            .exchange()
            .flatMap(resp -> resp.bodyToMono(Map.class))
            .flatMap(body -> {
                if(Integer.valueOf(401).equals(body.get("status"))){
                    return Mono.error(new ResponseStatusException(HttpStatus.UNAUTHORIZED, body.get("message").toString()));
                } else {
                    return Mono.just(body);
                }
            })
            .map(values -> new TokenService.UserSSO(values, keys))
            .map(userSSO -> {
                User user = new User();
                user.setIdSSO(ssoProvider.toString() + "#" + userSSO.id);
                user.setFirstName(userSSO.firstName);
                user.setLastName(userSSO.lastName);
                return user;
            });
}
 
開發者ID:SopraSteriaGroup,項目名稱:initiatives_backend_auth,代碼行數:26,代碼來源:TokenService.java

示例3: addComment

import reactor.core.publisher.Mono; //導入依賴的package包/類
@PostMapping("/comments")
public Mono<String> addComment(Mono<Comment> newComment) {
	if (commentSink != null) {
		return newComment
			.map(comment -> {
				commentSink.next(MessageBuilder
					.withPayload(comment)
					.setHeader(MessageHeaders.CONTENT_TYPE,
						MediaType.APPLICATION_JSON_VALUE)
					.build());
				return comment;
			})
			.flatMap(comment -> {
				meterRegistry
					.counter("comments.produced", "imageId", comment.getImageId())
					.increment();
				return Mono.just("redirect:/");
			});
	} else {
		return Mono.just("redirect:/");
	}
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:23,代碼來源:CommentController.java

示例4: index

import reactor.core.publisher.Mono; //導入依賴的package包/類
@GetMapping("/")
public Mono<String> index(Model model) {
	model.addAttribute("images",
		imageService
			.findAllImages()
			.flatMap(image ->
				Mono.just(image)
					.zipWith(repository.findByImageId(
						image.getId()).collectList()))
			.map(imageAndComments -> new HashMap<String, Object>(){{
				put("id", imageAndComments.getT1().getId());
				put("name", imageAndComments.getT1().getName());
				put("comments",
					imageAndComments.getT2());
			}}));
	model.addAttribute("extra",
		"DevTools can also detect code changes too");
	return Mono.just("index");
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:20,代碼來源:HomeController.java

示例5: manyToOne

import reactor.core.publisher.Mono; //導入依賴的package包/類
/**
 * Implements a stream -> unary call as {@link Flux} -> {@link Mono}, where the client transits a stream of
 * messages.
 */
public static <TRequest, TResponse> Mono<TResponse> manyToOne(
        Flux<TRequest> rxRequest,
        Function<StreamObserver<TResponse>, StreamObserver<TRequest>> delegate) {
    try {
        return Mono
                .<TResponse>create(emitter -> {
                    ReactiveProducerStreamObserver<TRequest, TResponse> reactiveProducerStreamObserver = new ReactiveProducerStreamObserver<>(
                            rxRequest,
                            emitter::success,
                            emitter::error,
                            Runnables.doNothing());
                    delegate.apply(
                            new CancellableStreamObserver<>(reactiveProducerStreamObserver,
                            reactiveProducerStreamObserver::cancel));
                    reactiveProducerStreamObserver.rxSubscribe();
                })
                .transform(Operators.lift(new SubscribeOnlyOnceLifter<TResponse>()));
    } catch (Throwable throwable) {
        return Mono.error(throwable);
    }
}
 
開發者ID:salesforce,項目名稱:reactive-grpc,代碼行數:26,代碼來源:ClientCalls.java

示例6: handle

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Override
public Mono<Void> handle(WebSocketSession session) {
	return session
		.receive()
		.log("inbound-incoming-chat-message")
		.map(WebSocketMessage::getPayloadAsText)
		.log("inbound-convert-to-text")
		.map(s -> session.getId() + ": " + s)
		.log("inbound-mark-with-session-id")
		.flatMap(this::broadcast)
		.log("inbound-broadcast-to-broker")
		.then();
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:14,代碼來源:InboundChatService.java

示例7: update

import reactor.core.publisher.Mono; //導入依賴的package包/類
public Mono<ServerResponse> update(ServerRequest req) {

        return Mono
            .zip(
                (data) -> {
                    Post p = (Post) data[0];
                    Post p2 = (Post) data[1];
                    p.setTitle(p2.getTitle());
                    p.setContent(p2.getContent());
                    return p;
                },
                this.posts.findById(req.pathVariable("id")),
                req.bodyToMono(Post.class)
            )
            .cast(Post.class)
            .flatMap(post -> this.posts.save(post))
            .flatMap(post -> ServerResponse.noContent().build());

    }
 
開發者ID:hantsy,項目名稱:spring-reactive-sample,代碼行數:20,代碼來源:DemoApplication.java

示例8: setUp

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Before
public void setUp() {

	operations.collectionExists(Person.class) //
			.flatMap(exists -> exists ? operations.dropCollection(Person.class) : Mono.just(exists)) //
			.flatMap(o -> operations.createCollection(Person.class, new CollectionOptions(1024 * 1024, 100, true))) //
			.then() //
			.block();

	repository
			.save(Flux.just(new Person("Walter", "White", 50), //
					new Person("Skyler", "White", 45), //
					new Person("Saul", "Goodman", 42), //
					new Person("Jesse", "Pinkman", 27))) //
			.then() //
			.block();

}
 
開發者ID:callistaenterprise,項目名稱:spring-react-one,代碼行數:19,代碼來源:ReactivePersonRepositoryIntegrationTest.java

示例9: setUp

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Before
public void setUp() {

	template.collectionExists(Person.class) //
			.flatMap(exists -> exists ? template.dropCollection(Person.class) : Mono.just(exists)) //
			.flatMap(exists -> template.createCollection(Person.class)) //
			.then() //
			.block();

	template
			.insertAll(Flux.just(new Person("Walter", "White", 50), //
					new Person("Skyler", "White", 45), //
					new Person("Saul", "Goodman", 42), //
					new Person("Jesse", "Pinkman", 27)).collectList())
			.then() //
			.block();
}
 
開發者ID:callistaenterprise,項目名稱:spring-react-one,代碼行數:18,代碼來源:ReactiveMongoTemplateIntegrationTest.java

示例10: testSingleWithTemplate

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Test
public void testSingleWithTemplate() {
	// tag::mono-template[]
	Employee e = new Employee();
	e.setFirstName("Bilbo");
	Example<Employee> example = Example.of(e);

	Mono<Employee> singleEmployee = operations.findOne(
		new Query(byExample(example)), Employee.class);
	// end::mono-template[]

	StepVerifier.create(singleEmployee)
		.expectNextMatches(employee -> {
			assertThat(employee).hasNoNullFieldsOrProperties();
			assertThat(employee.getFirstName()).isEqualTo("Bilbo");
			assertThat(employee.getLastName()).isEqualTo("Baggins");
			assertThat(employee.getRole()).isEqualTo("burglar");
			return true;
		})
		.expectComplete()
		.verify();
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:23,代碼來源:QueryTests.java

示例11: fromAddressNotFoundTest

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Test
void fromAddressNotFoundTest() {
    doReturn(LOCATION_NOT_FOUND).when(locationService).get(any());

    final GeographicCoordinates geographicCoordinates = GOOGLE_ADDRESS_MONO.transform(locationService::fromAddress)
            .onErrorResume(throwable -> {
                assertThat(throwable, instanceOf(GeoLocationNotFoundException.class));
                return Mono.empty();
            }).block();

    assertThat(geographicCoordinates, is(nullValue()));

    verify(locationService, times(1)).fromAddress(any());
    verify(locationService, times(1)).buildUrl(any());
    verify(locationService, times(1)).get(any());
    verify(locationService, times(1)).geometryLocation(any());

    reset(locationService);
}
 
開發者ID:LearningByExample,項目名稱:reactive-ms-example,代碼行數:20,代碼來源:GeoLocationServiceImplTests.java

示例12: oneRawImage

import reactor.core.publisher.Mono; //導入依賴的package包/類
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
	produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
	@PathVariable String filename) {
	// tag::try-catch[]
	return imageService.findOneImage(filename)
		.map(resource -> {
			try {
				return ResponseEntity.ok()
					.contentLength(resource.contentLength())
					.body(new InputStreamResource(
						resource.getInputStream()));
			} catch (IOException e) {
				return ResponseEntity.badRequest()
					.body("Couldn't find " + filename +
						" => " + e.getMessage());
			}
		});
	// end::try-catch[]
}
 
開發者ID:PacktPublishing,項目名稱:Learning-Spring-Boot-2.0-Second-Edition,代碼行數:22,代碼來源:UploadController.java

示例13: revokeAccessCertificate

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Override
@Transactional
public Mono<Boolean> revokeAccessCertificate(IssuerNonceAuthentication nonceAuthentication,
                                             RevokeAccessCertificateContext context) {
    requireNonNull(nonceAuthentication, "`nonceAuthentication` must not be null");
    requireNonNull(context, "`context` must not be null");

    IssuerEntity issuerEntity = findIssuerOrThrow(nonceAuthentication);
    verifyNonceAuthOrThrow(nonceAuthentication, issuerEntity.getPublicKey());

    AccessCertificateEntity accessCertificate = accessCertificateRepository
            .findByUuid(context.getAccessCertificateId().toString())
            .orElseThrow(() -> new NotFoundException("AccessCertificateEntity not found"));

    if (accessCertificate.getIssuerId() != issuerEntity.getId()) {
        log.warn("Mismatching issuer id for access cert {}: {} != {}", context.getAccessCertificateId(),
                accessCertificate.getIssuerId(), issuerEntity.getId());
        // do not expose information about existing access certs - hence: NotFoundException
        throw new NotFoundException("AccessCertificateEntity not found");
    }

    accessCertificateRepository.delete(accessCertificate);

    return Mono.just(true);
}
 
開發者ID:amvnetworks,項目名稱:amv-access-api-poc,代碼行數:26,代碼來源:AccessCertificateServiceImpl.java

示例14: shouldGetSession

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Test
public void shouldGetSession() throws Exception {

	// given
	String sessionId = UUID.randomUUID().toString();
	Document sessionDocument = new Document();

	given(this.mongoOperations.findById(sessionId, Document.class,
		ReactiveMongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME)).willReturn(Mono.just(sessionDocument));

	MongoSession session = new MongoSession();

	given(this.converter.convert(sessionDocument, TypeDescriptor.valueOf(Document.class),
			TypeDescriptor.valueOf(MongoSession.class))).willReturn(session);

	// when
	StepVerifier.create(this.repository.findById(sessionId))
		.expectNextMatches(retrievedSession -> {
			// then
			assertThat(retrievedSession).isEqualTo(session);
			return true;
		});
}
 
開發者ID:spring-projects,項目名稱:spring-session-data-mongodb,代碼行數:24,代碼來源:ReactiveMongoOperationsSessionRepositoryTest.java

示例15: create

import reactor.core.publisher.Mono; //導入依賴的package包/類
@Transactional public Mono<ServerResponse> create(ServerRequest request) {
  return request.bodyToMono(UserParam.class)
      .flatMap(param -> ServerResponse
          .status(HttpStatus.CREATED)
          .contentType(MediaType.APPLICATION_JSON_UTF8)
          .body(param2Po(param)
              .flatMap(userRepository::save), User.class)
          .switchIfEmpty(Mono.empty()));
}
 
開發者ID:saintdan,項目名稱:spring-webflux-microservices-boilerplate,代碼行數:10,代碼來源:UserHandler.java


注:本文中的reactor.core.publisher.Mono類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。