Java Code Examples for reactor.core.publisher.Mono#create()
The following examples show how to use
reactor.core.publisher.Mono#create() .
These examples are extracted from open source projects.
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 Project: device-simulator File: VertxMqttDeviceClient.java License: Apache License 2.0 | 6 votes |
@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 2
Source Project: titus-control-plane File: TitusClientImpl.java License: Apache License 2.0 | 6 votes |
@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 3
Source Project: jetlinks-community File: VertxTcpClient.java License: Apache License 2.0 | 6 votes |
@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 4
Source Project: titus-control-plane File: ReactorSerializedInvoker.java License: Apache License 2.0 | 6 votes |
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 Project: vertx-spring-boot File: VertxClientHttpRequest.java License: Apache License 2.0 | 6 votes |
@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 Project: vertx-spring-boot File: VertxWebServer.java License: Apache License 2.0 | 6 votes |
@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 7
Source Project: reactor-netty File: ServerTransport.java License: Apache License 2.0 | 5 votes |
/** * 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 8
Source Project: springboot-learning-example File: CityHandler.java License: Apache License 2.0 | 5 votes |
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 9
Source Project: spring-cloud-circuitbreaker-demo File: ReactiveHystrixCircuitBreaker.java License: Apache License 2.0 | 5 votes |
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 10
Source Project: smallrye-reactive-streams-operators File: MonoConverter.java License: Apache License 2.0 | 5 votes |
@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 11
Source Project: vertx-spring-boot File: VertxServerHttpResponse.java License: Apache License 2.0 | 5 votes |
@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 12
Source Project: reactor-netty File: PooledConnectionProvider.java License: Apache License 2.0 | 5 votes |
@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 13
Source Project: styx File: NettyConnectionFactory.java License: Apache License 2.0 | 5 votes |
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 14
Source Project: tools-journey File: CityRestController.java License: Apache License 2.0 | 4 votes |
@RequestMapping(method = RequestMethod.PUT) public Mono<Long> modifyCity(@RequestBody City city) { return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.updateCity(city))); }
Example 15
Source Project: titus-control-plane File: SpectatorInvocationHandler.java License: Apache License 2.0 | 4 votes |
@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 16
Source Project: springboot-learning-example File: CityHandler.java License: Apache License 2.0 | 4 votes |
public Mono<Long> save(City city) { return Mono.create(cityMonoSink -> cityMonoSink.success(cityRepository.save(city))); }
Example 17
Source Project: springboot-learning-example File: CityHandler.java License: Apache License 2.0 | 4 votes |
public Mono<Long> deleteCity(Long id) { cityRepository.deleteById(id); return Mono.create(cityMonoSink -> cityMonoSink.success(id)); }
Example 18
Source Project: styx File: StubConnectionFactory.java License: Apache License 2.0 | 4 votes |
@Override public Mono<Connection> createConnection(Origin origin, ConnectionSettings connectionPoolConfiguration) { return Mono.create(sink -> { sink.success(new StubConnection(origin)); }); }
Example 19
Source Project: tools-journey File: CityRestController.java License: Apache License 2.0 | 4 votes |
@RequestMapping(method = RequestMethod.POST) public Mono<Long> createCity(@RequestBody City city) { return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.saveCity(city))); }
Example 20
Source Project: tools-journey File: CityRestController.java License: Apache License 2.0 | 4 votes |
@RequestMapping(value = "/{id}", method = RequestMethod.GET) public Mono<City> findOneCity(@PathVariable("id") Long id) { return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.findCityById(id))); }