io.vertx.servicediscovery.ServiceDiscovery Java Examples

The following examples show how to use io.vertx.servicediscovery.ServiceDiscovery. 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: ConsulServiceImporterTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicImport() {
  services.add(buildService("10.1.10.12", "redis", "redis", null, 8000, "passing"));

  discovery = ServiceDiscovery.create(vertx);
  discovery.registerServiceImporter(new ConsulServiceImporter(),
          new JsonObject().put("host", "localhost").put("port", 5601));

  await().until(() -> getAllRecordsBlocking().size() > 0);
  List<Record> list = getAllRecordsBlocking();

  assertThat(list).hasSize(1);

  Record record = list.get(0);
  assertThat(record.getLocation().getString("host")).isEqualTo("10.1.10.12");
  assertThat(record.getLocation().getInteger("port")).isEqualTo(8000);
  assertThat(record.getLocation().getString("path")).isNull();
  assertThat(record.getName()).isEqualTo("redis");
  assertThat(record.getRegistration()).isNotEmpty();
}
 
Example #2
Source File: EventBusService.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup for a service record and if found, retrieve it and return the service object (used to consume the service).
 * This is a convenient method to avoid explicit lookup and then retrieval of the service. This method requires to
 * have the {@code clientClass} set with the expected set of client. This is important for usages not using Java so
 * you can pass the expected type.
 *
 * @param discovery     the service discovery
 * @param filter        the filter as json object
 * @param clientClass   the client class
 * @param resultHandler the result handler
 * @param <T>           the type of the client class
 * @return {@code null} - do not use
 */
static <T> T getServiceProxyWithJsonFilter(ServiceDiscovery discovery,
                                           JsonObject filter,
                                           Class<T> clientClass,
                                           Handler<AsyncResult<T>> resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed()) {
      resultHandler.handle(Future.failedFuture(ar.cause()));
    } else {
      if (ar.result() == null) {
        resultHandler.handle(Future.failedFuture("Cannot find service matching with " + filter));
      } else {
        ServiceReference service = discovery.getReference(ar.result());
        resultHandler.handle(Future.succeededFuture(service.getAs(clientClass)));
      }
    }
  });
  return null;
}
 
Example #3
Source File: DiscoveryRegistrarTest.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void should_Cleanup_Unused_Consumers_On_Closing_Managed_Discovery() {
    discoveryRegistrar = DiscoveryRegistrar.create(vertx);
    ServiceDiscovery discovery1 = discoveryRegistrar.startListening(
            new ServiceDiscoveryOptions().setName("discovery1"), record -> {}, refData -> {}).getDiscovery();
    ServiceDiscovery discovery2 = discoveryRegistrar.startListening(
            new ServiceDiscoveryOptions().setName("discovery1"), record -> {}, refData -> {}).getDiscovery();
    ServiceDiscovery discovery3 = discoveryRegistrar.startListening(
            new ServiceDiscoveryOptions().setName("discovery2").setAnnounceAddress("otherAnnounce"),
                    record -> {}, refData -> {}).getDiscovery();

    assertEquals(2, discoveryRegistrar.serviceDiscoveryNames().size());
    assertNotNull(discoveryRegistrar.getDiscovery("discovery1"));
    assertEquals(discoveryRegistrar.getDiscovery("discovery1"), discovery2);
    assertNotEquals(discoveryRegistrar.getDiscovery("discovery2"), discoveryRegistrar.getDiscovery("discovery3"));

    // TODO Complete test

    discovery1.close();
}
 
Example #4
Source File: MongoDataSourceExamples.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-data-source-service"),
    ar -> {
      if (ar.succeeded() && ar.result() != null) {
        // Retrieve the service reference
        ServiceReference reference = discovery.getReferenceWithConfiguration(
          ar.result(), // The record
          new JsonObject().put("username", "clement").put("password", "*****")); // Some additional metadata

        // Retrieve the service object
        MongoClient client = reference.get();

        // ...

        // when done
        reference.release();
      }
    });
}
 
Example #5
Source File: AuditVerticleTest.java    From vertx-microservices-workshop with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp(TestContext tc) {
  Async async = tc.async();
  vertx = Vertx.vertx();
  Record record = MessageSource.createRecord("portfolio-events", "portfolio", JsonObject
      .class);
  ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions()
      .setBackendConfiguration(new JsonObject().put("backend-name", DefaultServiceDiscoveryBackend.class.getName())))
      .publish(record,
          r -> {
            if (r.failed()) {
              r.cause().printStackTrace();
              tc.fail(r.cause());
            }
            vertx.deployVerticle(AuditVerticle.class.getName(), new DeploymentOptions().setConfig(CONFIGURATION), tc.asyncAssertSuccess(s -> async.complete()));
          });
}
 
Example #6
Source File: EventBusService.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup for a service record and if found, retrieve it and return the service object (used to consume the service).
 * This is a convenient method to avoid explicit lookup and then retrieval of the service. This method requires to
 * have the {@code clientClass} set with the expected set of client. This is important for usages not using Java so
 * you can pass the expected type.
 *
 * @param discovery     the service discovery
 * @param filter        the filter
 * @param clientClass   the client class
 * @param resultHandler the result handler
 * @param <T>           the type of the client class
 * @return {@code null} - do not use
 */
static <T> T getServiceProxy(ServiceDiscovery discovery,
                             Function<Record, Boolean> filter,
                             Class<T> clientClass,
                             Handler<AsyncResult<T>> resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed()) {
      resultHandler.handle(Future.failedFuture(ar.cause()));
    } else {
      if (ar.result() == null) {
        resultHandler.handle(Future.failedFuture("Cannot find service matching with " + filter));
      } else {
        ServiceReference service = discovery.getReference(ar.result());
        resultHandler.handle(Future.succeededFuture(service.getAs(clientClass)));
      }
    }
  });
  return null;
}
 
Example #7
Source File: MongoDataSourceExamples.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
public void example3(ServiceDiscovery discovery) {
  MongoDataSource.<JsonObject>getMongoClient(discovery,
    new JsonObject().put("name", "some-data-source-service"),
    new JsonObject().put("username", "clement").put("password", "*****"), // Some additional metadata
    ar -> {
      if (ar.succeeded()) {
        MongoClient client = ar.result();

        // ...

        // Dont' forget to release the service
        ServiceDiscovery.releaseServiceObject(discovery, client);

      }
    });
}
 
Example #8
Source File: EventBusService.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup for a service record and if found, retrieve it and return the service object (used to consume the service).
 * This is a convenient method to avoid explicit lookup and then retrieval of the service. This method requires to
 * have the {@code clientClass} set with the expected set of client. This is important for usages not using Java so
 * you can pass the expected type.
 *
 * @param discovery     the service discovery
 * @param filter        the filter as json object
 * @param clientClass   the client class
 * @param conf          the configuration for message delivery
 * @param resultHandler the result handler
 * @param <T>           the type of the client class
 * @return {@code null} - do not use
 */
static <T> T getServiceProxyWithJsonFilter(ServiceDiscovery discovery,
                                           JsonObject filter,
                                           Class<T> clientClass,
                                           JsonObject conf,
                                           Handler<AsyncResult<T>> resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed()) {
      resultHandler.handle(Future.failedFuture(ar.cause()));
    } else {
      if (ar.result() == null) {
        resultHandler.handle(Future.failedFuture("Cannot find service matching with " + filter));
      } else {
        ServiceReference service = discovery.getReferenceWithConfiguration(ar.result(), conf);
        resultHandler.handle(Future.succeededFuture(service.getAs(clientClass)));
      }
    }
  });
  return null;
}
 
Example #9
Source File: EventBusService.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup for a service record and if found, retrieve it and return the service object (used to consume the service).
 * This is a convenient method to avoid explicit lookup and then retrieval of the service. A filter based on the
 * request interface is used.
 *
 * @param discovery     the service discovery instance
 * @param itf           the service interface
 * @param resultHandler the result handler
 * @param <T>           the service interface
 * @return {@code null}
 */
@GenIgnore // Java only
static <T> T getProxy(ServiceDiscovery discovery, Class<T> itf, Handler<AsyncResult<T>>
  resultHandler) {
  JsonObject filter = new JsonObject().put("service.interface", itf.getName());
  discovery.getRecord(filter, ar -> {
    if (ar.failed()) {
      resultHandler.handle(Future.failedFuture(ar.cause()));
    } else {
      if (ar.result() == null) {
        resultHandler.handle(Future.failedFuture("Cannot find service matching with " + filter));
      } else {
        ServiceReference service = discovery.getReference(ar.result());
        resultHandler.handle(Future.succeededFuture(service.get()));
      }
    }
  });
  return null;
}
 
Example #10
Source File: JDBCDataSourceExamples.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
public void example3(ServiceDiscovery discovery) {
  JDBCDataSource.<JsonObject>getJDBCClient(discovery,
      new JsonObject().put("name", "some-data-source-service"),
      new JsonObject().put("username", "clement").put("password", "*****"), // Some additional metadata
      ar -> {
        if (ar.succeeded()) {
          JDBCClient client = ar.result();

          // ...

          // Dont' forget to release the service
          ServiceDiscovery.releaseServiceObject(discovery, client);

        }
      });
}
 
Example #11
Source File: EventBusService.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup for a service record and if found, retrieve it and return the service object (used to consume the service).
 * This is a convenient method to avoid explicit lookup and then retrieval of the service. A filter based on the
 * request interface is used.
 *
 * @param discovery     the service discovery instance
 * @param itf           the service interface
 * @param conf          the configuration for message delivery
 * @param resultHandler the result handler
 * @param <T>           the service interface
 * @return {@code null}
 */
@GenIgnore // Java only
static <T> T getProxy(ServiceDiscovery discovery, Class<T> itf, JsonObject conf, Handler<AsyncResult<T>> resultHandler) {
  JsonObject filter = new JsonObject().put("service.interface", itf.getName());
  discovery.getRecord(filter, ar -> {
    if (ar.failed()) {
      resultHandler.handle(Future.failedFuture(ar.cause()));
    } else {
      if (ar.result() == null) {
        resultHandler.handle(Future.failedFuture("Cannot find service matching with " + filter));
      } else {
        ServiceReference service = discovery.getReferenceWithConfiguration(ar.result(), conf);
        resultHandler.handle(Future.succeededFuture(service.get()));
      }
    }
  });
  return null;
}
 
Example #12
Source File: JDBCDataSourceExamples.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-data-source-service"),
      ar -> {
        if (ar.succeeded() && ar.result() != null) {
          // Retrieve the service reference
          ServiceReference reference = discovery.getReferenceWithConfiguration(
              ar.result(), // The record
              new JsonObject().put("username", "clement").put("password", "*****")); // Some additional metadata

          // Retrieve the service object
          JDBCClient client = reference.getAs(JDBCClient.class);

          // ...

          // when done
          reference.release();
        }
      });
}
 
Example #13
Source File: SchemaRegistrationTest.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    vertx = Vertx.vertx();
    options = new ServiceDiscoveryOptions().setName("theDiscovery")
            .setAnnounceAddress("theAnnounceAddress").setUsageAddress("theUsageAddress");
    discovery = ServiceDiscovery.create(vertx, options);
    record = new Record()
            .setName("theRecord")
            .setType(Queryable.SERVICE_TYPE)
            .setMetadata(new JsonObject().put("publisherId", "thePublisherId"))
            .setLocation(new JsonObject().put(Record.ENDPOINT, Queryable.ADDRESS_PREFIX + ".DroidQueries"))
            .setStatus(Status.UP);
    definition = SchemaDefinition.createInstance(droidsSchema,
            SchemaMetadata.create(new JsonObject().put("publisherId", "thePublisherId")));
    consumer = ProxyHelper.registerService(Queryable.class,
            vertx, definition, Queryable.ADDRESS_PREFIX + ".DroidQueries");
}
 
Example #14
Source File: RedisDataSourceExamples.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-redis-data-source-service"), ar -> {
      if (ar.succeeded() && ar.result() != null) {
        // Retrieve the service reference
        ServiceReference reference = discovery.getReference(ar.result());

        // Retrieve the service instance
        Redis client = reference.getAs(Redis.class);

        // ...

        // when done
        reference.release();
      }
    });
}
 
Example #15
Source File: KubernetesServerTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
private List<Record> getRecordsBlocking(ServiceDiscovery discovery) {
  CountDownLatch latch = new CountDownLatch(1);

  List<Record> records = new ArrayList<>();
  discovery.getRecords(s -> true, ar -> {
    records.addAll(ar.result());
    latch.countDown();
  });

  try {
    latch.await();
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
  return records;
}
 
Example #16
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 #17
Source File: APIGatewayVerticle.java    From vertx-blueprint-microservice with Apache License 2.0 6 votes vote down vote up
private void authUaaHandler(RoutingContext context) {
  if (context.user() != null) {
    JsonObject principal = context.user().principal();
    String username = null;  // TODO: Only for demo. Complete this in next version.
    // String username = KeycloakHelper.preferredUsername(principal);
    if (username == null) {
      context.response()
        .putHeader("content-type", "application/json")
        .end(new Account().setId("TEST666").setUsername("Eric").toString()); // TODO: no username should be an error
    } else {
      Future<AccountService> future = Future.future();
      EventBusService.getProxy(discovery, AccountService.class, future.completer());
      future.compose(accountService -> {
        Future<Account> accountFuture = Future.future();
        accountService.retrieveByUsername(username, accountFuture.completer());
        return accountFuture.map(a -> {
          ServiceDiscovery.releaseServiceObject(discovery, accountService);
          return a;
        });
      })
        .setHandler(resultHandlerNonEmpty(context)); // if user does not exist, should return 404
    }
  } else {
    context.fail(401);
  }
}
 
Example #18
Source File: GraphQLClient.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Get the GraphQL service proxy that is associated with the provided service record.
 *
 * @param discovery     the service discovery instance
 * @param record        the service record of a published GraphQL service
 * @param resultHandler the result handler
 */
static void getSchemaProxy(ServiceDiscovery discovery, Record record,
                           Handler<AsyncResult<Queryable>> resultHandler) {
    Objects.requireNonNull(discovery, "Service discovery cannot be null");
    Objects.requireNonNull(record, "Record cannot be null");
    Objects.requireNonNull(resultHandler, "Schema proxy result handler cannot be null");

    if (!SERVICE_TYPE.equals(record.getType())) {
        resultHandler.handle(Future.failedFuture("Record '" + record.getName() +
                "' is of wrong type '" + record.getType() + "'. Expected: " + SERVICE_TYPE));
    } else if (!Status.UP.equals(record.getStatus())) {
        resultHandler.handle(Future.failedFuture("Record status indicates service '" + record.getName() +
                "' is: " + record.getStatus() + ". Expected: " + Status.UP));
    } else if (record.getRegistration() == null) {
        resultHandler.handle(Future.failedFuture("Record '" + record.getName() +
                "' has no service discovery registration"));
    } else {
        ServiceReference reference = discovery.getReference(record);
        Queryable queryable = reference.cached() == null ? reference.get() : reference.cached();
        reference.release();
        resultHandler.handle(Future.succeededFuture(queryable));
    }
}
 
Example #19
Source File: GraphQLClient.java    From vertx-graphql-service-discovery with Apache License 2.0 6 votes vote down vote up
/**
 * Lookup a GraphQL service record using the provided filter and if found, retrieve the service proxy of type
 * {@link Queryable} used for querying.
 *
 * @param discovery     the service discovery instance
 * @param filter        the filter to select the schema
 * @param resultHandler the result handler
 */
static void getSchemaProxy(ServiceDiscovery discovery, JsonObject filter,
                           Handler<AsyncResult<Queryable>> resultHandler) {
    Objects.requireNonNull(discovery, "Service discovery cannot be null");
    Objects.requireNonNull(resultHandler, "Schema proxy result handler cannot be null");

    discovery.getRecord(filter, rh -> {
        if (rh.failed()) {
            resultHandler.handle(Future.failedFuture(rh.cause()));
        } else {
            if (rh.result() == null) {
                resultHandler.handle(Future.failedFuture("Failed to find schema proxy using filter " + filter));
            } else {
                Record record = rh.result();
                if (!SERVICE_TYPE.equals(record.getType())) {
                    resultHandler.handle(Future.failedFuture("Record '" + record.getName() +
                            "' is of wrong type '" + record.getType() + "'. Expected: " + SERVICE_TYPE));
                } else {
                    getSchemaProxy(discovery, rh.result(), resultHandler);
                }
            }
        }
    });
}
 
Example #20
Source File: HTTPEndpointExamples.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
public void example2_webclient(ServiceDiscovery discovery) {
  // Get the record
  discovery.getRecord(new JsonObject().put("name", "some-http-service"), ar -> {
    if (ar.succeeded() && ar.result() != null) {
      // Retrieve the service reference
      ServiceReference reference = discovery.getReference(ar.result());
      // Retrieve the service object
      WebClient client = reference.getAs(WebClient.class);

      // You need to path the complete path
      client.get("/api/persons").send(
        response -> {

          // ...

          // Dont' forget to release the service
          reference.release();

        });
    }
  });
}
 
Example #21
Source File: MongoDataSourceExamples.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
public void example1(ServiceDiscovery discovery) {
  Record record = MongoDataSource.createRecord(
    "some-data-source-service", // The service name
    new JsonObject().put("connection_string", "some mongo connection"), // The location
    new JsonObject().put("some-metadata", "some-value") // Some metadata
  );

  discovery.publish(record, ar -> {
    // ...
  });
}
 
Example #22
Source File: ServiceDiscoveryExamples.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
public void example1(Vertx vertx) {
  // Use default configuration
  ServiceDiscovery discovery = ServiceDiscovery.create(vertx);

  // Customize the configuration
  discovery = ServiceDiscovery.create(vertx,
      new ServiceDiscoveryOptions()
          .setAnnounceAddress("service-announce")
          .setName("my-name"));

  // Do something...

  discovery.close();
}
 
Example #23
Source File: ServiceDiscoveryBackendConsulExamples.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
public void configuration1(Vertx vertx) {
  ServiceDiscovery.create(vertx, new ServiceDiscoveryOptions()
    .setBackendConfiguration(
      new JsonObject()
        .put("defaultHost", "127.0.0.1")
        .put("dc", "my-dc")
    ));
}
 
Example #24
Source File: HttpEndpoint.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
/**
 * Convenient method that looks for a HTTP endpoint and provides the configured {@link HttpClient}. 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
 * @param resultHandler The result handler
 */
static void getClient(ServiceDiscovery discovery, Function<Record, Boolean> filter, Handler<AsyncResult<HttpClient>>
  resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed() || ar.result() == null) {
      resultHandler.handle(Future.failedFuture("No matching record"));
    } else {
      resultHandler.handle(Future.succeededFuture(discovery.<HttpClient>getReference(ar.result()).get()));
    }
  });
}
 
Example #25
Source File: CallbackTraderVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> done) throws Exception {

    String company = TraderUtils.pickACompany();
    int numberOfShares = TraderUtils.pickANumber();
    System.out.println("Java-Callback compulsive trader configured for company " + company + " and shares: " +
        numberOfShares);

    // TODO Complete the code to apply the trading _logic_ on each message received from the "market-data" message
    // source
    // ----

    // Retrieve service discovery
    Future<ServiceDiscovery> retrieveServiceDiscovery = getServiceDiscovery(vertx);

    // When the service discovery is retrieved, retrieve the portfolio service and market data
    retrieveServiceDiscovery.setHandler(discovery -> {

        // TODO 1 - Get the Future objects for the portfolio and market services. Just use the method given below

        // TODO 2 - Use CompositeFuture.all to "wait" until both future are completed.

        // TODO 3 - Attach a handler on the composite future, and call "initialize"

        // Remove it
        done.complete();
    });
    // ----

}
 
Example #26
Source File: RedisDataSource.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
/**
 * Convenient method that looks for a Redis data source and provides the configured {@link io.vertx.redis.client.Redis}.
 * 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, cannot be {@code null}
 * @param consumerConfiguration The additional consumer configuration
 * @param resultHandler         The result handler
 */
static void getRedisClient(ServiceDiscovery discovery, Function<Record, Boolean> filter, JsonObject
  consumerConfiguration,
                           Handler<AsyncResult<Redis>> resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed() || ar.result() == null) {
      resultHandler.handle(Future.failedFuture("No matching record"));
    } else {
      resultHandler.handle(Future.succeededFuture(
        discovery.<Redis>getReferenceWithConfiguration(ar.result(), consumerConfiguration).get()));
    }
  });
}
 
Example #27
Source File: EventBusServiceExamples.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
public void example3(ServiceDiscovery discovery) {
  EventBusService.getProxy(discovery, MyService.class, ar -> {
    if (ar.succeeded()) {
      MyService service = ar.result();

      // Dont' forget to release the service
      ServiceDiscovery.releaseServiceObject(discovery, service);
    }
  });
}
 
Example #28
Source File: JDBCDataSource.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
/**
 * Convenient method that looks for a JDBC datasource source and provides the configured {@link io.vertx.ext.jdbc.JDBCClient}. 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
 */
static void getJDBCClient(ServiceDiscovery discovery, JsonObject filter,
                          Handler<AsyncResult<JDBCClient>> resultHandler) {
  discovery.getRecord(filter, ar -> {
    if (ar.failed() || ar.result() == null) {
      resultHandler.handle(Future.failedFuture("No matching record"));
    } else {
      resultHandler.handle(Future.succeededFuture(discovery.<JDBCClient>getReference(ar.result()).get()));
    }
  });
}
 
Example #29
Source File: HttpEndpointTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublicationAndConsumptionWithConfigurationAsWebClient(TestContext context) {
  Async async = context.async();

  // Publish the service
  Record record = HttpEndpoint.createRecord("hello-service", "localhost", 8080, "/foo");
  discovery.publish(record, rec -> {
    Record published = rec.result();

    HttpEndpoint.getWebClient(discovery,
      new JsonObject().put("name", "hello-service"),
      new JsonObject().put("keepAlive", false), found -> {
        context.assertTrue(found.succeeded());
        context.assertTrue(found.result() != null);
        WebClient client = found.result();
        client.get("/foo").send(ar -> {
          if (ar.failed()) {
            context.fail(ar.cause());
          }
          HttpResponse<Buffer> response = ar.result();
          context.assertEquals(response.statusCode(), 200);
          context.assertEquals(response.getHeader("connection"), "close");
          context.assertEquals(response.body().toString(), "hello");

          ServiceDiscovery.releaseServiceObject(discovery, client);
          discovery.unpublish(published.getRegistration(), v -> async.complete());
        });
      });
  });
}
 
Example #30
Source File: MessageSourceExamples.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
public void example1(ServiceDiscovery discovery) {
  Record record1 = MessageSource.createRecord(
      "some-message-source-service", // The service name
      "some-address", // The event bus address
      JsonObject.class // The message payload type
  );

  Record record2 = MessageSource.createRecord(
      "some-other-message-source-service", // The service name
      "some-address", // The event bus address
      JsonObject.class, // The message payload type
      new JsonObject().put("some-metadata", "some value")
  );
}