io.vertx.core.eventbus.MessageConsumer Java Examples

The following examples show how to use io.vertx.core.eventbus.MessageConsumer. 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: VertxVaadin.java    From vertx-vaadin with MIT License 7 votes vote down vote up
private void configureSessionStore() {
    final Registration sessionInitListenerReg = this.service.addSessionInitListener(event -> {
        MessageConsumer<String> consumer = sessionExpiredHandler(vertx, msg ->
            Optional.of(event.getSession().getSession())
                .filter(session -> msg.body().equals(session.getId()))
                .ifPresent(WrappedSession::invalidate));
        AtomicReference<Registration> sessionDestroyListenerUnregister = new AtomicReference<>();
        sessionDestroyListenerUnregister.set(
            event.getService().addSessionDestroyListener(ev2 -> {
                consumer.unregister();
                sessionDestroyListenerUnregister.get().remove();
            })
        );

    });
    this.service.addServiceDestroyListener(event -> sessionInitListenerReg.remove());
}
 
Example #2
Source File: EventBusBridge.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
/**
 * Removes all subscriptions of the given connection
 *
 * @param connection the connection
 * @return the current instance of {@link Destination}
 */
@Override
public synchronized Destination unsubscribeConnection(StompServerConnection connection) {
  new ArrayList<>(subscriptions)
      .stream()
      .filter(subscription -> subscription.connection.equals(connection))
      .forEach(s -> {
        subscriptions.remove(s);
        Optional<Subscription> any = subscriptions.stream().filter(s2 -> s2.destination.equals(s.destination))
            .findAny();
        // We unregister the event bus consumer if there are no subscription on this address anymore.
        if (!any.isPresent()) {
          MessageConsumer<?> consumer = registry.remove(s.destination);
          if (consumer != null) {
            consumer.unregister();
          }
        }
      });
  return this;
}
 
Example #3
Source File: VertxRecorder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
void unregisterMessageConsumers() {
    CountDownLatch latch = new CountDownLatch(messageConsumers.size());
    for (MessageConsumer<?> messageConsumer : messageConsumers) {
        messageConsumer.unregister(ar -> {
            if (ar.succeeded()) {
                latch.countDown();
            }
        });
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Unable to unregister all message consumer methods", e);
    }
    messageConsumers.clear();
}
 
Example #4
Source File: VertxEventChannel.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void registerMonitor(Set<Class> types, EventMonitor monitor) {
    try {
        for (Class type : types) {
            EventManager manager = managers.get(type);
            if (manager == null) {
                manager = new EventManager();
                managers.put(type, manager);
                // TODO 需要防止路径冲突
                EventHandler handler = new EventHandler(type, manager);
                MessageConsumer<byte[]> consumer = bus.consumer(name + StringUtility.DOT + type.getName(), handler);
                CountDownLatch latch = new CountDownLatch(1);
                consumer.completionHandler((register) -> {
                    latch.countDown();
                });
                latch.await();
                consumers.put(type, consumer);
            }
            manager.attachMonitor(monitor);
        }
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
}
 
Example #5
Source File: VertxEventChannel.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void unregisterMonitor(Set<Class> types, EventMonitor monitor) {
    try {
        for (Class type : types) {
            EventManager manager = managers.get(type);
            if (manager != null) {
                manager.detachMonitor(monitor);
                if (manager.getSize() == 0) {
                    managers.remove(type);
                    MessageConsumer<byte[]> consumer = consumers.remove(type);
                    CountDownLatch latch = new CountDownLatch(1);
                    consumer.unregister((unregister) -> {
                        latch.countDown();
                    });
                    latch.await();
                }
            }
        }
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
}
 
Example #6
Source File: VertxVaadin.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private void configureSessionStore() {
    final Registration sessionInitListenerReg = this.service.addSessionInitListener(event -> {
        MessageConsumer<String> consumer = sessionExpiredHandler(vertx, msg ->
            Optional.of(event.getSession().getSession())
                .filter(session -> msg.body().equals(session.getId()))
                .ifPresent(WrappedSession::invalidate));
        AtomicReference<Registration> sessionDestroyListenerUnregister = new AtomicReference<>();
        sessionDestroyListenerUnregister.set(
            event.getService().addSessionDestroyListener(ev2 -> {
                consumer.unregister();
                sessionDestroyListenerUnregister.get().remove();
            })
        );

    });
    this.service.addServiceDestroyListener(event -> sessionInitListenerReg.remove());
}
 
Example #7
Source File: DefaultAudioConnection.java    From kyoko with MIT License 6 votes vote down vote up
@Override
public void destroy() {
    consumers.forEach(MessageConsumer::unregister);
    consumers.clear();

    if (closeFuture != null) closeFuture.complete(null);
    if (connection != null) connection.close(ConnectionStatus.NOT_CONNECTED);

    guild.catnip().closeVoiceConnection(guild.id());

    closeFuture = null;
    connection = null;
    handler = null;
    channel = null;
    endpoint = null;
    sessionId = null;
}
 
Example #8
Source File: Website.java    From excelastic with MIT License 6 votes vote down vote up
private HttpServer setupStatusService() {
    return vertx.createHttpServer().websocketHandler(websock -> {
        websock.writeFinalTextFrame(new JsonObject().put("message", getStatusServiceWelcomeMessage()).encode());

        AtomicReference<String> uploadId = new AtomicReference<>("");

        // sets up an event bus consumer to listen for import progress.
        MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer(IMPORT_PROGRESS, data -> {
            try {
                if (uploadId.get().equals(data.body().getString(UPLOAD_ID))) {
                    websock.writeFinalTextFrame(data.body().encode());
                }
            } catch (Throwable e) {
                websock.close();
            }
        });
        // we only support one message from the client - to set the upload ID to listen to.
        websock.handler(handler -> uploadId.set(handler.toJsonObject().getString(UPLOAD_ID)));

        // when the websocket is closed we should stop listening for status messages.
        websock.closeHandler(closed -> consumer.unregister());

        // when the websocket excepts we should also stop listening for status messages.
        websock.exceptionHandler(sock -> consumer.unregister());
    });
}
 
Example #9
Source File: MessageSourceExamples.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
public void example2(ServiceDiscovery discovery) {
  // Get the record
  discovery.getRecord(new JsonObject().put("name", "some-message-source-service"), ar -> {
    if (ar.succeeded() && ar.result() != null) {
      // Retrieve the service reference
      ServiceReference reference = discovery.getReference(ar.result());
      // Retrieve the service object
      MessageConsumer<JsonObject> consumer = reference.getAs(MessageConsumer.class);

      // Attach a message handler on it
      consumer.handler(message -> {
        // message handler
        JsonObject payload = message.body();
      });
    }
  });
}
 
Example #10
Source File: CacheBasedDeviceConnectionServiceTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Future<Void> givenAStartedService() {

    final Vertx vertx = mock(Vertx.class);
    doAnswer(invocation -> {
        final Promise<RemoteCacheContainer> result = Promise.promise();
        final Handler<Future<RemoteCacheContainer>> blockingCode = invocation.getArgument(0);
        final Handler<AsyncResult<RemoteCacheContainer>> resultHandler = invocation.getArgument(1);
        blockingCode.handle(result.future());
        resultHandler.handle(result.future());
        return null;
    }).when(vertx).executeBlocking(any(Handler.class), any(Handler.class));
    final EventBus eventBus = mock(EventBus.class);
    when(eventBus.consumer(anyString())).thenReturn(mock(MessageConsumer.class));
    when(vertx.eventBus()).thenReturn(eventBus);
    final Context ctx = mock(Context.class);

    final Promise<Void> startPromise = Promise.promise();
    svc.init(vertx, ctx);
    try {
        svc.start(startPromise);
    } catch (Exception e) {
        return Future.failedFuture(e);
    }
    return startPromise.future();
}
 
Example #11
Source File: RawOrderDispatcher.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
  super.start();
  MessageSource.<JsonObject>getConsumer(discovery,
    new JsonObject().put("name", "shopping-order-message-source"),
    ar -> {
      if (ar.succeeded()) {
        MessageConsumer<JsonObject> orderConsumer = ar.result();
        orderConsumer.handler(message -> {
          Order wrappedOrder = wrapRawOrder(message.body());
          dispatchOrder(wrappedOrder, message);
        });
        future.complete();
      } else {
        future.fail(ar.cause());
      }
    });
}
 
Example #12
Source File: SchemaRegistrar.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Registers a schema definition created by the
 * {@link GraphQLService}.
 * <p>
 * The provided registration is cloned, completed with publisher-related information, registered and then returned.
 *
 * @param partialRegistration the partially completed schema registration
 * @param options             the service discovery options to add
 * @param publishedHandler    the event handler to invoke on schema published events
 * @param unpublishedHandler  the event handler to invoke on schema unpublished events
 * @return the completed schema registration
 */
protected SchemaRegistration register(
        SchemaRegistration partialRegistration, ServiceDiscoveryOptions options,
        SchemaPublishedHandler<SchemaRegistration> publishedHandler,
        SchemaUnpublishedHandler<SchemaRegistration> unpublishedHandler) {

    // First start listening to schema events.
    registerSchemaEventConsumers(options, publishedHandler, unpublishedHandler);

    // Then register service consumer created from schema definition, if it was not registered yet.
    MessageConsumer<JsonObject> serviceConsumer = registerSchemaServiceConsumer(
            partialRegistration.getRecord(), partialRegistration.getSchemaDefinition());

    // Complete the schema registration
    SchemaRegistration fullRegistration = SchemaRegistration.create(partialRegistration.getDiscovery(), options,
            partialRegistration.getRecord(), partialRegistration.getSchemaDefinition(), serviceConsumer);

    return super.register(options.getName(), fullRegistration);
}
 
Example #13
Source File: EventBusBridge.java    From vertx-stomp with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a un-subscription request to the current {@link Destination}.
 *
 * @param connection the connection
 * @param frame      the {@code UNSUBSCRIBE} frame
 * @return {@code true} if the un-subscription has been handled, {@code false} otherwise.
 */
@Override
public synchronized boolean unsubscribe(StompServerConnection connection, Frame frame) {
  for (Subscription subscription : new ArrayList<>(subscriptions)) {
    if (subscription.connection.equals(connection)
        && subscription.id.equals(frame.getId())) {

      boolean r = subscriptions.remove(subscription);
      Optional<Subscription> any = subscriptions.stream().filter(s -> s.destination.equals(subscription.destination)).findAny();
      // We unregister the event bus consumer if there are no subscription on this address anymore.
      if (!any.isPresent()) {
        MessageConsumer<?> consumer = registry.remove(subscription.destination);
        if (consumer != null) {
          consumer.unregister();
        }
      }
      return r;
    }
  }
  return false;
}
 
Example #14
Source File: GraphQLService.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
/**
 * Publish a GraphQL schema for querying.
 * <p>
 * On success a {@link SchemaRegistration} is returned. It contains the message consumer of the
 * {@link Queryable} service proxy that supplies the published {@link SchemaDefinition}, the published service
 * discovery record, and the {@link ServiceDiscovery} it was published to.
 * <p>
 * Note that unless invoked from a {@link SchemaPublisher} a
 * client needs to keep hold of the returned {@link Record} as long as it is published.
 *
 * @param vertx         the vert.x instance
 * @param discovery     the service discovery instance
 * @param definition    the service proxy instance exposing the graphql schema
 * @param resultHandler the result handler that returns the registration
 */
static void publish(Vertx vertx, ServiceDiscovery discovery, SchemaDefinition definition,
                    Handler<AsyncResult<SchemaRegistration>> resultHandler) {

    Objects.requireNonNull(vertx, "Vertx cannot be null");
    Objects.requireNonNull(discovery, "Service discovery cannot be null");
    Objects.requireNonNull(definition, "GraphQL queryable cannot be null");
    Objects.requireNonNull(resultHandler, "Publication result handler cannot be null");

    // TODO Caching proxy ok?

    final MessageConsumer<JsonObject> serviceConsumer;
    if (definition.metadata().get("publisherId") == null) {
        serviceConsumer = ProxyHelper.registerService(
                Queryable.class, vertx, definition, definition.serviceAddress());
    } else {
        // Publisher handles service instantiation, manages consumer.
        serviceConsumer = null;
    }

    Record record = new Record()
            .setType(SERVICE_TYPE)
            .setName(definition.schemaName())
            .setMetadata(definition.metadata().toJson())
            .setLocation(new JsonObject().put(Record.ENDPOINT, definition.serviceAddress()));

    discovery.publish(record, rh -> {
        if (rh.succeeded()) {
            resultHandler.handle(Future.succeededFuture(
                    SchemaRegistration.create(discovery, null, rh.result(), definition, serviceConsumer)));
        } else {
            resultHandler.handle(Future.failedFuture(rh.cause()));
        }
    });
}
 
Example #15
Source File: ProxyHelper.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
public static <T> MessageConsumer<JsonObject> registerLocalService(Class<T> clazz, Vertx vertx, T service, String address,
                                                              boolean topLevel,
                                                              long timeoutSeconds) {
  return new ServiceBinder(vertx)
    .setAddress(address)
    .setTopLevel(topLevel)
    .setTimeoutSeconds(timeoutSeconds)
    .registerLocal(clazz, service);
}
 
Example #16
Source File: CallbackTraderVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
private void initialize(Future<Void> done, String company, int numberOfShares,
                        Future<PortfolioService> retrieveThePortfolioService, Future<MessageConsumer<JsonObject>> retrieveTheMarket,
                        AsyncResult<CompositeFuture> ar) {
    if (ar.failed()) {
        done.fail(ar.cause());
    } else {
        PortfolioService portfolio = retrieveThePortfolioService.result();
        MessageConsumer<JsonObject> consumer = retrieveTheMarket.result();
        consumer.handler(message -> TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, message.body()));
        done.complete();
    }
}
 
Example #17
Source File: Examples.java    From vertx-service-proxy with Apache License 2.0 5 votes vote down vote up
public void unregister(Vertx vertx) {
  ServiceBinder binder = new ServiceBinder(vertx);

  // Create an instance of your service implementation
  SomeDatabaseService service = new SomeDatabaseServiceImpl();
  // Register the handler
  MessageConsumer<JsonObject> consumer = binder
    .setAddress("database-service-address")
    .register(SomeDatabaseService.class, service);

  // ....

  // Unregister your service.
  binder.unregister(consumer);
}
 
Example #18
Source File: EventBusTest.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testEndToEndAfterFailure() {
  long now = System.currentTimeMillis();
  String address = TestUtils.randomAlphaString(10);
  String testSuiteName = TestUtils.randomAlphaString(10);
  String testCaseName = TestUtils.randomAlphaString(10);
  TestReporter testReporter = new TestReporter();
  MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer(address, EventBusCollector.create(vertx, testReporter).asMessageHandler());
  RuntimeException error = new RuntimeException("the_runtime_exception");
  consumer.completionHandler(ar -> {
    assertTrue(ar.succeeded());
    TestSuite suite = TestSuite.create(testSuiteName).
        test(testCaseName, context -> {
          try {
            Thread.sleep(10);
          } catch (InterruptedException ignore) {
          }
        }).after(context -> {
      throw error;
    });
    suite.run(vertx, new TestOptions().addReporter(new ReportOptions().setTo("bus:" + address)));
  });
  testReporter.await();
  assertEquals(1, testReporter.results.size());
  TestResult result1 = testReporter.results.get(0);
  assertEquals(testCaseName, result1.name());
  assertTrue(result1.succeeded());
  assertTrue(result1.beginTime() >= now);
  assertTrue(result1.durationTime() >= 10);
  assertEquals(1, testReporter.exceptions.size());
  Throwable cause = testReporter.exceptions.get(0);
  assertTrue(cause instanceof RuntimeException);
  assertEquals(error.getMessage(), cause.getMessage());
  assertTrue(Arrays.equals(error.getStackTrace(), cause.getStackTrace()));
  consumer.unregister();
}
 
Example #19
Source File: GeneratorVerticle.java    From vertx-starter with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Promise<Void> startPromise) {
  vertx.fileSystem().readFile("keywords", kar -> {
    if (kar.succeeded()) {

      Set<String> keywords = NEWLINE_REGEX.splitAsStream(kar.result().toString())
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .collect(toSet());

      generatorService = new GeneratorService(vertx, keywords);

      MessageConsumer<VertxProject> consumer = vertx.eventBus().consumer(Topics.PROJECT_REQUESTED);
      consumer.handler(this::onProjectRequested).completionHandler(ar -> {
        if (ar.succeeded()) {

          log.info(
            "\n----------------------------------------------------------\n\t" +
              "{} is running!\n" +
              "----------------------------------------------------------",
            GeneratorVerticle.class.getSimpleName()
          );

          startPromise.complete();

        } else {
          startPromise.fail(ar.cause());
        }
      });

    } else {
      startPromise.fail(kar.cause());
    }
  });
}
 
Example #20
Source File: CallbackTraderVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
private void initialize(Future<Void> done, String company, int numberOfShares,
                        Future<PortfolioService> retrieveThePortfolioService, Future<MessageConsumer<JsonObject>> retrieveTheMarket,
                        AsyncResult<CompositeFuture> ar) {
    if (ar.failed()) {
        done.fail(ar.cause());
    } else {
        PortfolioService portfolio = retrieveThePortfolioService.result();
        MessageConsumer<JsonObject> consumer = retrieveTheMarket.result();
        consumer.handler(message -> TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, message.body()));
        done.complete();
    }
}
 
Example #21
Source File: AuditVerticle.java    From microtrader with MIT License 5 votes vote down vote up
/**
 * Starts the verticle asynchronously. The the initialization is completed, it calls
 * `complete()` on the given {@link Future} object. If something wrong happens,
 * `fail` is called.
 *
 * @param future the future to indicate the completion
 */
@Override
public void start(Future<Void> future) throws ClassNotFoundException {
    super.start();

    // Get configuration
    config = ConfigFactory.load();

    // creates the jdbc client.
    JsonObject jdbcConfig = new JsonObject(config.getObject("jdbc").render(ConfigRenderOptions.concise()));
    jdbc = JDBCClient.createNonShared(vertx, jdbcConfig);
    Class.forName(jdbcConfig.getString("driverclass"));

    // Start HTTP server and listen for portfolio events
    EventBus eventBus = vertx.eventBus();
    Future<HttpServer> httpEndpointReady = configureTheHTTPServer();
    httpEndpointReady.setHandler(ar -> {
       if (ar.succeeded()) {
           MessageConsumer<JsonObject> portfolioConsumer = eventBus.consumer(config.getString("portfolio.address"));
           portfolioConsumer.handler(message -> {
               storeInDatabase(message.body());
           });
           future.complete();
       } else {
           future.fail(ar.cause());
       }
    });

    publishHttpEndpoint("audit", config.getString("http.host"), config.getInt("http.public.port"), config.getString("http.root"), ar -> {
        if (ar.failed()) {
            ar.cause().printStackTrace();
        } else {
            System.out.println("Audit (Rest endpoint) service published : " + ar.succeeded());
        }
    });
}
 
Example #22
Source File: AuditVerticle.java    From microtrader with MIT License 5 votes vote down vote up
private Future<MessageConsumer<JsonObject>> retrieveThePortfolioMessageSource() {
    Future<MessageConsumer<JsonObject>> future = Future.future();
    MessageSource.getConsumer(discovery,
            new JsonObject().put("name", "portfolio-events"),
            future.completer()
    );
    return future;
}
 
Example #23
Source File: CompulsiveTraderVerticle.java    From microtrader with MIT License 5 votes vote down vote up
@Override
public void start(Future<Void> future) {
    super.start();

    // Get configuration
    config = ConfigFactory.load();

    String company = TraderUtils.pickACompany();
    int numberOfShares = TraderUtils.pickANumber();

    EventBus eventBus = vertx.eventBus();
    EventBusService.getProxy(discovery, PortfolioService.class, ar -> {
        if (ar.failed()) {
            System.out.println("Portfolio service could not be retrieved: " + ar.cause());
        } else {
            // Our services:
            PortfolioService portfolio = ar.result();
            MessageConsumer<JsonObject> marketConsumer = eventBus.consumer(config.getString("market.address"));

            // Listen to the market...
            marketConsumer.handler(message -> {
                JsonObject quote = message.body();
                TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, quote);
            });
        }
    });
}
 
Example #24
Source File: ApplicationLauncher.java    From excelastic with MIT License 5 votes vote down vote up
/**
 * Waits until there is a connection to the ElasticSearch server and then
 * attempts to open the browser if one is available to the import website.
 */
private void waitForElasticServerAvailability() {
    MessageConsumer<?> consumer = vertx.eventBus().consumer(ES_STATUS);
    consumer.handler(message -> {
        logger.openingBrowser(message.body().toString());
        try {
            Desktop.getDesktop().browse(new URI(Configuration.getWebsiteURL()));
        } catch (Exception e) {
            logger.displayNotAvailable(e);
        }
        consumer.pause();
    });
}
 
Example #25
Source File: VertxEventBusMetricsTest.java    From vertx-micrometer-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDiscardMessages(TestContext context) {
  vertx = Vertx.vertx(new VertxOptions().setMetricsOptions(new MicrometerMetricsOptions()
    .setPrometheusOptions(new VertxPrometheusOptions().setEnabled(true))
    .setEnabled(true)))
    .exceptionHandler(t -> context.exceptionHandler().handle(t));

  int num = 10;
  EventBus eb = vertx.eventBus();
  MessageConsumer<Object> consumer = eb.consumer("foo");
  consumer.setMaxBufferedMessages(num);
  consumer.pause();
  consumer.handler(msg -> fail("should not be called"));
  for (int i = 0; i < num; i++) {
    eb.send("foo", "the_message-" + i);
  }
  eb.send("foo", "last");

  waitForValue(vertx, context, "vertx.eventbus.discarded[side=local]$COUNT", value -> value.intValue() == 1);
  List<RegistryInspector.Datapoint> datapoints = listDatapoints(startsWith("vertx.eventbus"));
  assertThat(datapoints).contains(dp("vertx.eventbus.pending[side=local]$VALUE", 10));

  // Unregister => discard all remaining
  consumer.unregister();
  waitForValue(vertx, context, "vertx.eventbus.discarded[side=local]$COUNT", value -> value.intValue() == 11);
  datapoints = listDatapoints(startsWith("vertx.eventbus"));
  assertThat(datapoints).contains(dp("vertx.eventbus.pending[side=local]$VALUE", 0));
}
 
Example #26
Source File: MessageSourceExamples.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
public void example3(ServiceDiscovery discovery) {
  MessageSource.<JsonObject>getConsumer(discovery, new JsonObject().put("name", "some-message-source-service"), ar -> {
    if (ar.succeeded()) {
      MessageConsumer<JsonObject> consumer = ar.result();

      // Attach a message handler on it
      consumer.handler(message -> {
        // message handler
        JsonObject payload = message.body();
      });
      // ...
    }
  });
}
 
Example #27
Source File: ServiceDiscoveryExamples.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
public void example5(ServiceDiscovery discovery, Record record1, Record record2) {
  ServiceReference reference1 = discovery.getReference(record1);
  ServiceReference reference2 = discovery.getReference(record2);

  // Then, gets the service object, the returned type depends on the service type:
  // For http endpoint:
  HttpClient client = reference1.getAs(HttpClient.class);
  // For message source
  MessageConsumer consumer = reference2.getAs(MessageConsumer.class);

  // When done with the service
  reference1.release();
  reference2.release();
}
 
Example #28
Source File: MessageSource.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
/**
 * Convenient method that looks for a message source and provides the configured {@link MessageConsumer}. The
 * async result is marked as failed is there are no matching services, or if the lookup fails.
 *
 * @param discovery     The service discovery instance
 * @param filter        The filter, optional
 * @param resultHandler The result handler
 * @param <T>           The class of the message
 */
static <T> void getConsumer(ServiceDiscovery discovery, JsonObject filter,
                            Handler<AsyncResult<MessageConsumer<T>>>
                                resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed() || ar.result() == null) {
      resultHandler.handle(Future.failedFuture("No matching record"));
    } else {
      resultHandler.handle(Future.succeededFuture(discovery.<MessageConsumer<T>>getReference(ar.result()).get()));
    }
  });
}
 
Example #29
Source File: MessageSource.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
/**
 * Convenient method that looks for a message source and provides the configured {@link MessageConsumer}. The
 * async result is marked as failed is there are no matching services, or if the lookup fails.
 *
 * @param discovery     The service discovery instance
 * @param filter        The filter, must not be {@code null}
 * @param resultHandler The result handler
 * @param <T>           The class of the message
 */
static <T> void getConsumer(ServiceDiscovery discovery, Function<Record, Boolean> filter,
                            Handler<AsyncResult<MessageConsumer<T>>>
                              resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed() || ar.result() == null) {
      resultHandler.handle(Future.failedFuture("No matching record"));
    } else {
      resultHandler.handle(Future.succeededFuture(discovery.<MessageConsumer<T>>getReference(ar.result()).get()));
    }
  });
}
 
Example #30
Source File: SSEConnectionImpl.java    From vertx-sse with Apache License 2.0 5 votes vote down vote up
@Override
public SSEConnection close() {
	try {
		context.response().end(); // best effort
	} catch(VertxException | IllegalStateException e) {
		// connection has already been closed by the browser
		// do not log to avoid performance issues (ddos issue if client opening and closing alot of connections abruptly)
	}
	if (!consumers.isEmpty()) {
		consumers.forEach(MessageConsumer::unregister);
	}
	return this;
}