当前位置: 首页>>代码示例>>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;未经允许,请勿转载。