Java Code Examples for reactor.core.publisher.Mono#delay()

The following examples show how to use reactor.core.publisher.Mono#delay() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MonoToListenableFutureAdapterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void cancellation() {
	Mono<Long> mono = Mono.delay(Duration.ofSeconds(60));
	Future<Long> future = new MonoToListenableFutureAdapter<>(mono);

	assertTrue(future.cancel(true));
	assertTrue(future.isCancelled());
}
 
Example 2
Source File: MonoToListenableFutureAdapterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void cancellation() {
	Mono<Long> mono = Mono.delay(Duration.ofSeconds(60));
	Future<Long> future = new MonoToListenableFutureAdapter<>(mono);

	assertTrue(future.cancel(true));
	assertTrue(future.isCancelled());
}
 
Example 3
Source File: ReactorEssentialsTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Test
public void startStopStreamProcessing() throws Exception {
    Mono<?> startCommand = Mono.delay(Duration.ofSeconds(1));
    Mono<?> stopCommand = Mono.delay(Duration.ofSeconds(3));
    Flux<Long> streamOfData = Flux.interval(Duration.ofMillis(100));

    streamOfData
        .skipUntilOther(startCommand)
        .takeUntilOther(stopCommand)
        .subscribe(System.out::println);

    Thread.sleep(4000);
}
 
Example 4
Source File: R046_Timeout.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
/**
 * TODO Add fallback to {@link Flux#timeout(Duration)}
 * It should return -1 when timeout of 100ms occurs.
 */
@Test
public void timeout() throws Exception {
	//given
	final Mono<Long> withTimeout = Mono.delay(ofMillis(200));

	//when
	final Mono<Long> withFallback = withTimeout;

	//then
	withFallback
			.as(StepVerifier::create)
			.expectNext(-1L)
			.verifyComplete();
}
 
Example 5
Source File: HttpSupplier.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
private Mono<?> transform(ClientResponse response) {
	HttpStatus status = response.statusCode();
	if (!status.is2xxSuccessful()) {
		if (this.props.isDebug()) {
			logger.info("Delaying supplier based on status=" + response.statusCode());
		}
		return Mono.delay(Duration.ofSeconds(1));
	}
	return response.bodyToMono(this.props.getSource().getType())
			.map(value -> message(response, value));
}
 
Example 6
Source File: RateLimitRetryOperator.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Mono<Long> retryMono(Duration delay) {
    if (delay == Duration.ZERO) {
        return Mono.just(0L);
    } else {
        return Mono.delay(delay, backoffScheduler);
    }
}
 
Example 7
Source File: RequestStream.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void next(SignalType signal) {
    Mono<Long> timer = sleepTime.isZero() ? Mono.just(0L) : Mono.delay(sleepTime, timedTaskScheduler);
    timer.subscribe(l -> {
        if (log.isDebugEnabled()) {
            log.debug("[B:{}] Ready to consume next request after {}", id.toString(), signal);
        }
        sleepTime = Duration.ZERO;
        request(1);
    }, t -> log.error("[B:{}] Error while scheduling next request", id.toString(), t));
}
 
Example 8
Source File: Consumer.java    From liiklus with MIT License 4 votes vote down vote up
public static void main(String[] args) {
    // This variable should point to your Liiklus deployment (possible behind a Load Balancer)
    String liiklusTarget = getLiiklusTarget();

    var channel = NettyChannelBuilder.forTarget(liiklusTarget)
            .directExecutor()
            .usePlaintext()
            .build();

    var subscribeAction = SubscribeRequest.newBuilder()
            .setTopic("events-topic")
            .setGroup("my-group")
            .setAutoOffsetReset(AutoOffsetReset.EARLIEST)
            .build();

    var stub = ReactorLiiklusServiceGrpc.newReactorStub(channel);

    // Send an event every second
    Flux.interval(Duration.ofSeconds(1))
            .onBackpressureDrop()
            .concatMap(it -> stub.publish(
                    PublishRequest.newBuilder()
                            .setTopic(subscribeAction.getTopic())
                            .setKey(ByteString.copyFromUtf8(UUID.randomUUID().toString()))
                            .setLiiklusEvent(
                                    LiiklusEvent.newBuilder()
                                            .setId(UUID.randomUUID().toString())
                                            .setType("com.example.event")
                                            .setSource("/example")
                                            .setDataContentType("text/plain")
                                            .setData(ByteString.copyFromUtf8(UUID.randomUUID().toString()))
                            )
                            .build()
            ))
            .subscribe();

    // Consume the events
    Function<Integer, Function<ReceiveReply.Record, Publisher<?>>> businessLogic = partition -> record -> {
        log.info("Processing record from partition {} offset {}", partition, record.getOffset());

        // simulate processing
        return Mono.delay(Duration.ofMillis(200));
    };

    stub
            .subscribe(subscribeAction)
            .filter(it -> it.getReplyCase() == SubscribeReply.ReplyCase.ASSIGNMENT)
            .map(SubscribeReply::getAssignment)
            .doOnNext(assignment -> log.info("Assigned to partition {}", assignment.getPartition()))
            .flatMap(assignment -> stub
                    // Start receiving the events from a partition
                    .receive(ReceiveRequest.newBuilder().setAssignment(assignment).build())
                    .window(1000) // ACK every 1000th record
                    .concatMap(
                            batch -> batch
                                    .map(ReceiveReply::getRecord)
                                    .delayUntil(businessLogic.apply(assignment.getPartition()))
                                    .sample(Duration.ofSeconds(5)) // ACK every 5 seconds
                                    .onBackpressureLatest()
                                    .delayUntil(record -> {
                                        log.info("ACKing partition {} offset {}", assignment.getPartition(), record.getOffset());
                                        return stub.ack(
                                                AckRequest.newBuilder()
                                                        .setTopic(subscribeAction.getTopic())
                                                        .setGroup(subscribeAction.getGroup())
                                                        .setGroupVersion(subscribeAction.getGroupVersion())
                                                        .setPartition(assignment.getPartition())
                                                        .setOffset(record.getOffset())
                                                        .build()
                                        );
                                    }),
                            1
                    )
            )
            .blockLast();
}