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

The following examples show how to use reactor.core.publisher.Mono#create() . 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: TitusClientImpl.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Task> getTask(String taskId) {
    logger.debug("Getting Task information about taskId {}", taskId);
    return Mono.create(sink -> attachCallerId(jobManagementService, CLIENT_ID)
            .findTask(TaskId.newBuilder().setId(taskId).build(), new StreamObserver<Task>() {
                @Override
                public void onNext(Task task) {
                    sink.success(task);
                }

                @Override
                public void onError(Throwable t) {
                    logger.error("Error fetching task information for task ID = {}", taskId);
                    apiErrors.incrementAndGet();
                    sink.error(t);
                }

                @Override
                public void onCompleted() {

                }
            }));
}
 
Example 2
Source File: VertxTcpClient.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Boolean> send(TcpMessage message) {
    return Mono.<Boolean>create((sink) -> {
        if (socket == null) {
            sink.error(new SocketException("socket closed"));
            return;
        }
        socket.write(Buffer.buffer(message.getPayload()), r -> {
            keepAlive();
            if (r.succeeded()) {
                sink.success(true);
            } else {
                sink.error(r.cause());
            }
        });
    });
}
 
Example 3
Source File: VertxWebServer.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void stop() throws WebServerException {
    if (server == null) {
        return;
    }

    Mono<Void> future = Mono.create(sink -> server.close(result -> {
        if (result.succeeded()) {
            sink.success();
        } else {
            sink.error(result.cause());
        }
    }));

    future
        .doOnTerminate(() -> server = null)
        .block(Duration.ofSeconds(5));
}
 
Example 4
Source File: ReactorSerializedInvoker.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public Mono<T> submit(Mono<T> action) {
    Preconditions.checkState(!shutdownFlag, "ReactorQueue has been shutdown");
    Preconditions.checkNotNull(action);

    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

    return Mono.create(sink -> {
        metrics.onSubmit();

        ActionHandler actionHandler = new ActionHandler(action, sink, stackTrace);
        if (!actionHandlers.offer(actionHandler)) {
            metrics.onQueueFull();
            sink.error(actionHandler.newException(new IllegalStateException("Queue is full")));
            return;
        }
        metrics.setQueueSize(actionHandlers.size());

        if (shutdownFlag) {
            actionHandler.terminate();
        } else {
            worker.schedule(this::drain);
        }
    });
}
 
Example 5
Source File: VertxClientHttpRequest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> chunks) {
    Mono<Void> writeCompletion = Mono.create(sink -> {
        logger.debug("Subscribing to body publisher");
        Subscriber<DataBuffer> subscriber = new WriteStreamSubscriber.Builder<HttpClientRequest, DataBuffer>()
            .writeStream(delegate)
            .endHook(sink)
            .nextHandler((stream, value) -> stream.write(bufferConverter.toBuffer(value)))
            .build();
        chunks.subscribe(subscriber);
    });

    Mono<Void> endCompletion = Mono.create(sink -> {
        logger.debug("Completing request after writing");
        delegate.end();
        sink.success();
    });

    return doCommit(() -> writeCompletion.then(endCompletion));
}
 
Example 6
Source File: VertxMqttDeviceClient.java    From device-simulator with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Boolean> send(EncodedMessage message) {
    return Mono.create(sink -> {
        if (!(message instanceof MqttMessage)) {
            sink.error(new UnsupportedOperationException("unsupported message type:" + message.getClass()));
            return;
        }
        MqttMessage mqtt = ((MqttMessage) message);

        client.publish(mqtt.getTopic()
                , Buffer.buffer(mqtt.getPayload())
                , MqttQoS.valueOf(mqtt.getQosLevel())
                , mqtt.isDup()
                , mqtt.isRetain(), result -> {
                    if (result.succeeded()) {
                        sink.success(true);
                    } else {
                        sink.error(result.cause());
                    }
                });

    });
}
 
Example 7
Source File: MonoConverter.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
public <X> Mono fromCompletionStage(CompletionStage<X> cs) {
    return Mono.create(sink -> cs.whenComplete((X v, Throwable e) -> {
        if (e != null) {
            sink.error(e instanceof CompletionException ? e.getCause() : e);
        } else if (v != null) {
            sink.success(v);
        } else {
            sink.success();
        }
    }));
}
 
Example 8
Source File: NettyConnectionFactory.java    From styx with Apache License 2.0 5 votes vote down vote up
public Mono<Connection> createConnection(Origin origin, ConnectionSettings connectionSettings, SslContext sslContext) {
    return Mono.create(sink -> {
        ChannelFuture channelFuture = openConnection(origin, connectionSettings);

        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                sink.success(new NettyConnection(origin, channelFuture.channel(), httpRequestOperationFactory,
                        httpConfig, sslContext, sendSni, sniHost));
            } else {
                sink.error(new OriginUnreachableException(origin, future.cause()));
            }
        });
    });
}
 
Example 9
Source File: PooledConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public final Mono<? extends Connection> acquire(
		TransportConfig config,
		ConnectionObserver connectionObserver,
		@Nullable Supplier<? extends SocketAddress> remote,
		@Nullable AddressResolverGroup<?> resolverGroup) {
	Objects.requireNonNull(remote, "remoteAddress");
	Objects.requireNonNull(resolverGroup, "resolverGroup");
	return Mono.create(sink -> {
		SocketAddress remoteAddress = Objects.requireNonNull(remote.get(), "Remote Address supplier returned null");
		PoolKey holder = new PoolKey(remoteAddress, config.channelHash());
		PoolFactory<T> poolFactory = poolFactory(remoteAddress);
		InstrumentedPool<T> pool = channelPools.computeIfAbsent(holder, poolKey -> {
			if (log.isDebugEnabled()) {
				log.debug("Creating a new [{}] client pool [{}] for [{}]", name, poolFactory, remoteAddress);
			}

			InstrumentedPool<T> newPool = createPool(config, poolFactory, remoteAddress, resolverGroup);

			if (poolFactory.metricsEnabled || config.metricsRecorder() != null) {
				PooledConnectionProviderMetrics.registerMetrics(name,
						poolKey.hashCode() + "",
						Metrics.formatSocketAddress(remoteAddress),
						newPool.metrics());
			}
			return newPool;
		});

		pool.acquire(Duration.ofMillis(poolFactory.pendingAcquireTimeout))
		    .subscribe(createDisposableAcquire(connectionObserver, config.channelOperationsProvider(),
		            poolFactory.pendingAcquireTimeout, pool, sink));
	});
}
 
Example 10
Source File: VertxServerHttpResponse.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> writeWithInternal(Publisher<? extends DataBuffer> chunks) {
    return Mono.create(sink -> {
        logger.debug("Subscribing to body publisher");
        Subscriber<DataBuffer> subscriber = new WriteStreamSubscriber.Builder<HttpServerResponse, DataBuffer>()
            .writeStream(delegate)
            .endHook(sink)
            .nextHandler((stream, value) -> stream.write(bufferConverter.toBuffer(value)))
            .build();
        chunks.subscribe(subscriber);
    });
}
 
Example 11
Source File: ReactiveHystrixCircuitBreaker.java    From spring-cloud-circuitbreaker-demo with Apache License 2.0 5 votes vote down vote up
public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback) {
	HystrixObservableCommand<T> command = createCommand(toRun, fallback);

	return Mono.create(s -> {
		Subscription sub = command.toObservable().subscribe(s::success, s::error, s::success);
		s.onCancel(sub::unsubscribe);
	});
}
 
Example 12
Source File: CityHandler.java    From springboot-learning-example with Apache License 2.0 5 votes vote down vote up
public Mono<Long> deleteCity(Long id) {

        // 缓存存在,删除缓存
        String key = "city_" + id;
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            redisTemplate.delete(key);

            LOGGER.info("CityHandler.deleteCity() : 从缓存中删除城市 ID >> " + id);
        }

        cityRepository.deleteById(id);
        return Mono.create(cityMonoSink -> cityMonoSink.success(id));
    }
 
Example 13
Source File: ServerTransport.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Binds the {@link ServerTransport} and returns a {@link Mono} of {@link DisposableServer}. If
 * {@link Mono} is cancelled, the underlying binding will be aborted. Once the {@link
 * DisposableServer} has been emitted and is not necessary anymore, disposing the main server
 * loop must be done by the user via {@link DisposableServer#dispose()}.
 *
 * @return a {@link Mono} of {@link DisposableServer}
 */
public Mono<? extends DisposableServer> bind() {
	CONF config = configuration();
	Objects.requireNonNull(config.bindAddress(), "bindAddress");

	Mono<? extends DisposableServer> mono =  Mono.create(sink -> {
		SocketAddress local = Objects.requireNonNull(config.bindAddress().get(), "Bind Address supplier returned null");
		if (local instanceof InetSocketAddress) {
			InetSocketAddress localInet = (InetSocketAddress) local;

			if (localInet.isUnresolved()) {
				local = AddressUtils.createResolved(localInet.getHostName(), localInet.getPort());
			}
		}

		boolean isDomainSocket = false;
		DisposableBind disposableServer;
		if (local instanceof DomainSocketAddress) {
			isDomainSocket = true;
			disposableServer = new UdsDisposableBind(sink, config, local);
		}
		else {
			disposableServer = new InetDisposableBind(sink, config, local);
		}

		ConnectionObserver childObs =
				new ChildObserver(config.defaultChildObserver().then(config.childObserver()));
		Acceptor acceptor = new Acceptor(config.childEventLoopGroup(), config.channelInitializer(childObs, null, true),
				config.childOptions, config.childAttrs, isDomainSocket);
		TransportConnector.bind(config, new AcceptorInitializer(acceptor), local, isDomainSocket)
		                  .subscribe(disposableServer);
	});

	if (config.doOnBind() != null) {
		mono = mono.doOnSubscribe(s -> config.doOnBind().accept(config));
	}
	return mono;
}
 
Example 14
Source File: CityHandler.java    From springboot-learning-example with Apache License 2.0 4 votes vote down vote up
public Mono<Long> save(City city) {
    return Mono.create(cityMonoSink -> cityMonoSink.success(cityRepository.save(city)));
}
 
Example 15
Source File: CityHandler.java    From springboot-learning-example with Apache License 2.0 4 votes vote down vote up
public Mono<Long> deleteCity(Long id) {
    cityRepository.deleteById(id);
    return Mono.create(cityMonoSink -> cityMonoSink.success(id));
}
 
Example 16
Source File: StubConnectionFactory.java    From styx with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Connection> createConnection(Origin origin, ConnectionSettings connectionPoolConfiguration) {
    return Mono.create(sink -> {
        sink.success(new StubConnection(origin));
    });
}
 
Example 17
Source File: CityRestController.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public Mono<Long> createCity(@RequestBody City city) {
    return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.saveCity(city)));
}
 
Example 18
Source File: CityRestController.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Mono<City> findOneCity(@PathVariable("id") Long id) {
    return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.findCityById(id)));
}
 
Example 19
Source File: SpectatorInvocationHandler.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
protected Mono<Object> afterMono(Method method, Mono<Object> result, Long aLong) {
    long methodExitTime = clock.wallTime();

    return Mono.create(sink -> {
        long subscriptionTime = clock.wallTime();

        registry.counter(
                RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
                tags(
                        "method", method.getName(),
                        "subscriptionStage", "subscribed"
                )
        ).increment();
        reportSubscriptionExecutionTime(method, methodExitTime, subscriptionTime);

        AtomicBoolean emittedValue = new AtomicBoolean();
        Disposable subscription = result
                .doOnCancel(() -> {
                    registry.counter(
                            RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
                            tags(
                                    "method", method.getName(),
                                    "subscriptionStage", "unsubscribed"
                            )
                    ).increment();
                }).subscribe(
                        next -> {
                            emittedValue.set(true);
                            registry.counter(
                                    RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
                                    tags(
                                            "method", method.getName(),
                                            "subscriptionStage", "onSuccess",
                                            "monoWithValue", "true"
                                    )
                            ).increment();
                            reportExecutionTime(method, subscriptionTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_MONO_SUCCESS);

                            sink.success(next);
                        },
                        error -> {
                            registry.counter(
                                    RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
                                    tags(
                                            "method", method.getName(),
                                            "subscriptionStage", "onError",
                                            "exception", getExceptionName(error)
                                    )
                            ).increment();
                            reportExecutionTime(method, subscriptionTime, TAG_STATUS_ERROR, TAG_CALL_STAGE_ON_MONO_SUCCESS);

                            sink.error(error);
                        },
                        () -> {
                            if (!emittedValue.get()) {
                                registry.counter(
                                        RESULT_SUBSCRIPTION_COUNT_METRIC_NAME,
                                        tags(
                                                "method", method.getName(),
                                                "subscriptionStage", "onSuccess",
                                                "monoWithValue", "false"
                                        )
                                ).increment();
                                reportExecutionTime(method, subscriptionTime, TAG_STATUS_SUCCESS, TAG_CALL_STAGE_ON_MONO_SUCCESS);

                                sink.success();
                            }
                        }
                );

        sink.onCancel(subscription);
    });
}
 
Example 20
Source File: CityRestController.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT)
public Mono<Long> modifyCity(@RequestBody City city) {
    return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.updateCity(city)));
}